我正在使用Entity Framework Code First方法。我有这些课程。当然,他们还有其他领域,但他们与这个问题没有联系。
public class User
{
public int Id { get; set; }
public Role Role { get; set; }
public int HouseholdId { get; set; }
public virtual Household Household { get; set; }
}
public class Household
{
private ICollection<User> users;
public Household()
{
users = new HashSet<User>();
}
public int Id { get; set; }
public DateTime DateCreated { get; set; }
public virtual ICollection<User> Users
{
get { return users; }
set { users = value; }
}
}
我在OnModelCreating方法中应用了以下设置:
modelBuilder.Entity<User>()
.HasRequired(u => u.Household)
.WithMany()
.WillCascadeOnDelete(false);
当我运行应用程序时,除了生成的User表中还有一个外键添加到其设计中之外,一切都是正确的:
用户表:
Id
Role
HouseholdId
**Household_Id**
为什么会这样?
答案 0 :(得分:1)
只需从代码中删除它:
modelBuilder.Entity<User>()
.HasRequired(u => u.Household)
.WithMany()
.WillCascadeOnDelete(false);
编辑:
如果您需要WillCascadeOnDelete(false)
并且无法删除此代码,请尝试以下操作:
modelBuilder.Entity<User>()
.HasRequired(u => u.Household)
.WithMany(t => t.Users)
.WillCascadeOnDelete(false);