我在尝试映射现有的旧数据库时遇到问题。在这个例子中,一个国家有很多城市。
问题是 City 表的外键不是 Country 表的主键
表定义
CREATE TABLE [dbo].[CD_Country](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Code] [char](2) NOT NULL,
[Name] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_CD_Country] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[CD_City](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Code] [char](3) NOT NULL,
[Name] [nvarchar](50) NOT NULL,
[CountryCode] [char](2) NOT NULL,
CONSTRAINT [PK_CD_City] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
我正在尝试做这样的事情,但我得到了例外。
“导航属性 'Country' 到连接表 'CD_Country' 的映射无效。'Test_SOLEF.City' 类型的每个关键属性必须在映射中恰好包含一次。”
public static class Test
{
public static void DoIt()
{
using (TestEFContext context = new TestEFContext())
{
foreach (Country country in context.Coutries.ToList())
{
Console.WriteLine(string.Format("{0} has {1} cities.", country.Name, country.Cities.Count));
}
}
}
}
public class TestEFContext : DbContext
{
public IDbSet<Country> Coutries { get; set; }
public IDbSet<City> Cities { get; set; }
public TestEFContext()
{
ObjectContext.ContextOptions.LazyLoadingEnabled = true;
}
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
// city
modelBuilder.Entity<City>()
.HasKey(p => p.Id)
.MapSingleType()
.ToTable("CD_City");
modelBuilder.Entity<City>()
.Property(c => c.Id).IsIdentity();
modelBuilder.Entity<City>()
.HasOptional(c => c.Country)
.WithMany(c => c.Cities)
.Map(
"CD_Country",
(city, country) => new
{
CountryCode = city.CountryCode,
Code = country.Code
});
// country
modelBuilder.Entity<Country>()
.HasKey(p => p.Id)
.MapSingleType()
.ToTable("CD_Country");
}
}
public class City
{
public int Id {get;set;}
public string Code {get;set;}
public string Name {get;set;}
public string CountryCode {get;set;}
public virtual Country Country {get;set;}
}
public class Country
{
public int Id {get;set;}
public string Code {get;set;}
public string Name {get;set;}
public virtual ICollection<City> Cities {get;set;}
}