我有两个实体引用一对多。当实体框架创建表时,它会创建两个外键,一个用于我用流畅界面指定的键,另一个用于ICollection。我如何摆脱重复的外键?实体框架4.1代码第一外键ID的
public class Person
{
public long RecordId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Username { get; set; }
public long DepartmentId { get; set; }
public virtual Department Department { get; set; }
}
public class Department
{
public long RecordId { get; set; }
public string Name { get; set; }
public virtual ICollection<Person> People { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>()
.HasRequired(p => p.Department)
.WithMany()
.HasForeignKey(p => p.DepartmentId)
.WillCascadeOnDelete(false);
}
谢谢!
可以这样工作吗? : [ForeignKey(“Department”)] public long DepartmentId {get;组; } – billy 2012-03-16 14:40:22
@billy:这不是100%相同,因为注释不会禁用级联删除。如果你不想禁用级联删除,那么它的工作,是的。但是你甚至不需要注释,因为命名约定会自动检测外键属性。 – Slauma 2012-03-16 14:50:50
超级,谢谢! – billy 2012-03-16 15:30:18