Entity framework EF 4.0-编码一对多-Fluent API
我有以下两门课:Entity framework EF 4.0-编码一对多-Fluent API,entity-framework,Entity Framework,我有以下两门课: public class Person { public int Id { get; set; } public string FullName { get; set; } } public class Trip { public int Id { get; set; } public string Name { get; set; } public virtual IEnumerable<Person> Persons
public class Person
{
public int Id { get; set; }
public string FullName { get; set; }
}
public class Trip
{
public int Id { get; set; }
public string Name { get; set; }
public virtual IEnumerable<Person> Persons { get; set; }
}
公共类人物
{
公共int Id{get;set;}
公共字符串全名{get;set;}
}
公务舱旅行
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共虚拟IEnumerable Persons{get;set;}
}
正如你所看到的,一次旅行可以有一个或多个人
我试图使用EntityConfiguration来正确构建数据库,但无法使其正常工作。。。我对它的用法很困惑:
public class TripConfiguration : EntityTypeConfiguration<Trip>
{
internal TripConfiguration()
{
// ???
}
}
公共类TripConfiguration:EntityTypeConfiguration
{
内部TripConfiguration()
{
// ???
}
}
要使应用程序正常运行,我需要编写什么:
this.HasRequired(x => x.Person)
.WithMany(x => x.Trips)
.HasForeignKey(x => x.PersonId);
你的班级:
public class Person
{
public int Id { get; set; }
public string FullName { get; set; }
public virtual ICollection<Trip> Trips { get; set;}
}
public class Trip
{
public int Id { get; set; }
public string Name { get; set; }
public int PersonId { get; set; }
public virtual Person Person { get; set; }
}
公共类人物
{
公共int Id{get;set;}
公共字符串全名{get;set;}
公共虚拟ICollection Trips{get;set;}
}
公务舱旅行
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共int PersonId{get;set;}
公共虚拟人{get;set;}
}
据我所知,EF不支持unique FK(如果我错了,请纠正我)。所以你必须自己检查。这不是一对多关系,这是一个多对多关系,你需要在关系的两边都有集合。EF将代表您创建joiner表。由于现在您不能只配置一次旅行中的人员,因此在创建joiner表后,您需要在joiner表中创建一个唯一约束,以确保发生这种情况,因为EF尚未通过配置支持唯一键约束
public class Person
{
public int Id { get; set; }
public string FullName { get; set; }
public virtual ICollection<Trip> Trips { get; set; }
}
public class Trip
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Person> Persons { get; set; }
}
公共类人物
{
公共int Id{get;set;}
公共字符串全名{get;set;}
公共虚拟ICollection Trips{get;set;}
}
公务舱旅行
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共虚拟ICollection人员{get;set;}
}
然后
class PersonConfiguration:EntityTypeConfiguration
{
公共人员配置()
{
这个.有很多(t=>t.Trips).有很多(t=>t.person);
}
}
我编辑了我的问题。一个人不能在同一次旅行中不止一次。但一个人可以多次旅行。
class PersonConfiguration : EntityTypeConfiguration<Person>
{
public PersonConfiguration()
{
this.HasMany(t => t.Trips).WithMany(t => t.Persons);
}
}