Entity Framework .net core 中与模型相关的数据库上下文问题

Entity Framework Db context issue in .net core related to Models

我正在尝试像下面这样创建两个表时出现一些 EF 错误。

public class Student : ModelsBase
    {
        public string AdharNumber { get; set; }
        public byte Religion { get; set; }
        public int CategoryID { get; set; }
        public string Cast { get; set; }
        public string SubCast { get; set; }
        public string Photo { get; set; }
        public DateTime DateOfJoining { get; set; } = DateTime.Now;

        [Required]
        public ICollection<Address> TemporaryAddress { get; set; }

        [Required]
        public ICollection<Address> PermanentAddress { get; set; }
}

 public class Address : ModelsBase
    {
        public string DoorNo { get; set; }
        public string StreetLocality { get; set; }
        public string Landmark { get; set; }
        public string City { get; set; }
        public int Taluk { get; set; }
        public int District { get; set; }
        public int State { get; set; }
        public string Pincode { get; set; }
        public bool IsPermanent { get; set; } = true;
        public bool IsDefault { get; set; } = true;

        [ForeignKey("Student")]
        public Guid StudentId { get; set; }
    }

尝试运行“添加迁移命令”时出现以下错误

Both relationships between 'Address' and 'Student.PermanentAddress' and between 'Address' and 'Student.TemporaryAddress' could use {'StudentId'} as the foreign key. To resolve this, configure the foreign key properties explicitly in 'OnModelCreating' on at least one of the relationships

请帮忙。谢谢!

你的问题是,从地址方面你有一个 Many-to-1 和一个学生,但从学生方面你想要 2x 1-to-Many 关系。

因为关系实际上只是来自学生的 1-to-Many 要区分临时地址和永久地址:

public class Student : ModelsBase
{
    public string AdharNumber { get; set; }
    public byte Religion { get; set; }
    public int CategoryID { get; set; }
    public string Cast { get; set; }
    public string SubCast { get; set; }
    public string Photo { get; set; }
    public DateTime DateOfJoining { get; set; } = DateTime.Now;

    [Required]
    public ICollection<Address> Addresses { get; set; } = new List<Address>();


    [NotMapped]
    public ICollection<Address> TemporaryAddresses => Addresses.Where(x => !x.IsPermanent).ToList();

    [NotMapped]
    public ICollection<Address> PermanentAddresses => Addresses.Where(x => x.IsPermanent).ToList();

}

对于 1-to-many 个集合,我建议将它们初始化为空列表以避免空引用异常,尤其是在禁用延迟加载的情况下。

这里需要注意的是,从 EF 的角度来看,Student 只有 Addresses 集合,不要尝试在查询表达式中使用 TemporaryAddresses 或 PermanentAddresses,因为它们是未映射的访问器。如果您想根据永久地址进行过滤,则必须通过地址进行过滤,并在查询中包含关于 IsPermanent 的条件。

例如:

// Not valid...
var studentsInDetroit = context.Students.Where(x => x.PermanentAddresses.Any(a => a.City == "Detroit")).ToList();

// Valid...
var studentsInDetroit = context.Students.Where(x => x.Addresses.Any(a => a.IsPermanent && a.City == "Detroit")).ToList();

因此,通常我不建议在实体中使用未映射的访问器。通常最好让实体代表纯 domain/data 状态并将其投射到视图模型,这些模型更关心将数据拆分为更适合消费的形式。