我想要一张书桌、一张客户表和一张借款表。Customers表应该与Loans表具有一对多的关系。Books表还应该与Loans表具有一对多的关系。
为了模拟这种行为,在我的C#代码中,我声明了类Loan,它有一个类型为Customer Object的字段和另一个类型为Book Object的字段。
因此,在数据库中,贷款实体有两个字段:一个称为CustomerID(类型为int),另一个称为BookID(类型为int)。在代码中,我需要检索属于某个客户的所有贷款的列表。当我这样做时,确实返回了Loans对象的列表,但是对于每个对象,字段CustomerID和BookID都是null
。这是因为在数据库中,EF Core将它们存储为int,而在我的C#代码类中,它们是Customer和Book类型的对象。
我的创建表的方法是错误的吗?还有,我的问题应该有什么解决方案?提前感谢,我是EF Core的新手,因此,如果有任何帮助,我将不胜感激。
Customer.cs
public class Customer : Person
{
public DateTime DateJoined { get; set; }
public bool Status { get; set; }
[Required(ErrorMessage = "Please enter a valid email!")]
public string Email { get; set; } = string.Empty;
[Required(ErrorMessage = "Please enter a valid password")]
[StringLength(20,ErrorMessage = "The password can contain up to 20 characters")]
[MinLength(5,ErrorMessage = "The password can be at least 5 characters long")]
public string Password { get; set; } = string.Empty;
}
Book.cs
public class Book
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
public string? ImageUrl { get; set; }
public string? Cathegory { get; set; }
public int PublicationYear { get; set; }
public int CopiesAvailable { get; set; }
public string Description { get; set; } = string.Empty;
public bool IsBookOfTheMonth { get; set; }
public Author Author { get; set; } = default!;
}
Loan.cs
public class Loan
{
public int Id { get; set; }
public DateTime DateBorrowed { get; set; }
public int Status { get; set; }
public Customer Customer { get; set; } = default!;
public Book Book { get; set; } = default!;
}
1条答案
按热度按时间eanckbw91#
需要使用
Include()
方法加载相关数据:https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager
此外,建议在实体中定义外键属性:
Https://learn.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key#fully-defined-relationships