假设我有两个类 Country
和 Currency
我想用EF在它们之间创建一个关系。
public class Country
{
public long Id {get; set;}
public string Name {get; set;}
public long? CurrencyId {get; set;}
public Currency Currency {get; set;}
}
public class Currency
{
public long Id {get; set;}
public string Name {get; set;}
public long? CountryId {get; set;}
public Country Country {get; set;}
}
我不能管理这个,我有一些模型在同一类型的。像 User
和 Organization
.
安 Organization
有 Nullable UserId
和 User
拥有 Nullable organization
. 如何管理这个问题?
你完全可以有这样的关系,但它们必须正确配置,有时你必须插入实体,然后再更新它们,以绕过插入时而不是提交时的FK执行。
特别是当两个实体之间有多个关系时,EF没有约定来匹配反导航属性。
EG
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int DepartmentId { get; set; }
[InverseProperty(nameof(EfCore3Test.Department.Members))]
public Department Department { get; set; }
[InverseProperty(nameof(EfCore3Test.Department.Manager))]
public virtual ICollection<Department> ManagedDepartments { get; } = new HashSet<Department>();
}
public class Department
{
public int Id { get; set; }
public virtual ICollection<Person> Members { get; } = new HashSet<Person>();
public Person Manager { get; set; }
public int ManagerId { get; set; }
}
而你通常不能在所有的FK上都有级联行为,所以你至少要配置一个不级联。
modelBuilder.Entity<Department>()
.HasMany(d => d.Members)
.WithOne(m => m.Department)
.OnDelete(DeleteBehavior.NoAction);
public class Country
{
public long Id {get; set;}
public string Name {get; set;}
public long? CurrencyId {get; set;}
[ForeignKey("CurrencyId")]
public virtual Currency Currency {get; set;}
}
public class Currency
{
public long Id {get; set;}
public string Name {get; set;}
public long? CountryId {get; set;}
[ForeignKey("CountryId")]
public virtual Country Country {get; set;}
}
你将需要参考 using System.ComponentModel.DataAnnotations.Schema;