我正在嘗試創建如下所示的兩個表,但出現了一些 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
請幫忙。謝謝!
uj5u.com熱心網友回復:
您的問題是,從事物的地址方面,您有一個與單個學生的多對一,但從事物的學生方面,您想要 2x 一對多的關系。
由于關系實際上只是您想要區分臨時地址和永久地址的學生的一對多:
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();
}
對于一對多的集合,我建議將它們初始化為一個空串列以避免空參考例外,尤其是在禁用延遲加載的情況下。
這里需要注意的是,從 EF 的角度來看,Student 只有 Addresses 集合,不要嘗試在查詢運算式中使用 TemporaryAddresses 或 PermanentAddresses,因為它們是未映射的訪問器。如果要根據永久地址進行過濾,則必須通過 Addresses 進行過濾,并在查詢中包含 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();
因此,通常我不建議在物體中使用未映射的訪問器。通常最好留下代表純域/資料狀態的物體并將其投影到視圖模型,這些模型可能更關心將資料拆分為更可口的形式以供使用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/426635.html
