现在忽略您对多个国家实体的非规范化引用,您可以编写以下内容:
public class Country
{
[Key]
public int CountryID { get; set; }
[MaxLength(20)]
public string Name { get; set; }
}
public class Person
{
public int PersonID { get; set; }
[MaxLength(20)]
public string Name { get; set; }
public Country Country1 { get; set; }
public Country Country2 { get; set; }
public Country Country3 { get; set; }
}
当然,您还需要 DbContext:
public class Context : DbContext
{
public DbSet<Person> People { get; set; }
public DbSet<Country> Countries { get; set; }
public Context(string dbName)
:base (dbName)
{
}
}
这将导致表模式反映您的原始要求。
但是请注意,如果您这样声明类:
public class Country
{
[Key]
public int CountryID { get; set; }
[MaxLength(20)]
public string Name { get; set; }
public ICollection<Person> People { get; set; }
}
public class Person
{
public int PersonID { get; set; }
[MaxLength(20)]
public string Name { get; set; }
public ICollection<Country> Countries { get; set; }
}
在这种情况下,EF 将创建一个多对多连接表,允许您将任意数量的国家与任意数量的人关联起来:
CREATE TABLE [CountryPersons]
(
[CountryCountryID] int NOT NULL,
[PersonPersonID] int NOT NULL
);
请注意,EF 推断多对多关系是由于 People in countries 的集合和 Country in People 的集合。
HTH。