嗨,我有3或4张桌子,其中第4张是生成的很多对很多
员工>操作员>操作员仓库>仓库
这是模特
public class Employee
{
public int Id { get; set; }
public string Name{ get; set; }
public int UserId { get;set; }
public virtual User User { get; set; }
public Operator Operator { get; set; }
}
public class Operator
{
public int Id { get; set; }
public int EmployeeId { get; set; }
public Emlpoyee Emlpoyee { get; set; }
public ICollection<Warehouse> Warehouses { get; set; }
}
public class Warehouse
{
public int Id { get; set; }
public string Name{ get; set; }
public ICollection<Operator> Operators { get; set; }
}
在创建模型时,我做到了
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Employee>()
.HasRequired(u => u.Operator)
.WithRequiredPrincipal(c => c.Employee);
}
员工和操作员需要一对一的关系,但是在尝试更新数据库时出现错误
对象'PK_dbo.Operator'依赖于列'Id'。 ALTER TABLE DROP COLUMN ID失败,因为一个或多个对象访问此列。
这里有个额外的说明
已经存在以前的一对一关系,遵循相同的方式并且可以正常工作
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public virtual Employee Employee { get; set; }
public ICollection<Role> Roles { get; set; }
}
modelBuilder.Entity<User>()
.HasRequired(u => u.Employee)
.WithRequiredPrincipal(c => c.User);