如何在 Entity Framework Core 中获取具有导航属性的实体?我在 docs.microsoft
中看到我必须使用 .Include()
并且它在一个项目中工作,但这次它不工作。
模型.cs
public class UniversityModel
{
public int ID { get; set; }
public string Name { get; set; }
public string LongDescription { get; set; }
public string Address { get; set; }
public List<UniSession> Sessions { get; set; }
public DateTime Date { get; set; }
public List<UniEmail> Emails { get; set; }
public List<UniPhone> Phones { get; set; }
}
我正在使用它的导航属性访问 UniversityModel。
UniversityModel university = await _context.Universities
.Include(u => u.Phones)
.Include(u => u.Emails)
.Include(u => u.Sessions)
.SingleOrDefaultAsync(u => u.ID == id);
它正在正确获取 university
但不包括导航属性。
为清楚起见,请查看下面的Model
,所有导航属性模型都与大学的外键相同。
public class UniEmail
{
public int ID { get; set; }
public int UniversityId { get; set; }
[StringLength(50)]
public string Email { get; set; }
}
我如何正确地包含所有导航属性有什么问题?如果我的包含代码是错误的,那么它在另一个项目中是如何工作的?
最佳答案
问题是您的实体模型不遵循 EF Core 约定,并且您没有使用流畅的配置。尽管 EF 通过集合导航属性发现关系,但由于没有反向引用导航属性并且 UniversityId
字段未标识为 FK,因此 EF 将 FK 映射到 shadow property。称为 UniversityModelId
。
EF Core FK 命名约定在 Fully Defined Relationships 中进行了解释文档部分:
If the dependent entity contains a property named <primary key property name>, <navigation property name><primary key property name>, or <principal entity name><primary key property name> then it will be configured as the foreign key.
换句话说,如果满足以下条件,UniversityId
将按惯例被视为 FK:
(1) UniversityModel
类被称为University
(2) UniversityModel
类的 ID
属性被称为 UniversityID
(并用 [Key]
属性标记,因为它会不符合PK约定)
(3) 添加名为 University
的反向导航属性:
public UniversityModel University { get; set; }
public int UniversityId { get; set; }
当然,它可以用流畅的 API 显式映射:
modelBuilder.Entity<UniversityModel>()
.HasMany(e => e.Emails) // with collection navigation property
.WithOne() // and no reference navigation property
.HasForeignKey(e => e.UniversityId); // and foreign key
关于c# - 在 Entity Framework Core 中获取具有导航属性的实体的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48871947/