我的问题是访问 Web 应用程序中第二级关系的相关实体。未找到与 EF7 相关的正确答案。
让我们采用以下 3 个类的示例:一对多 - x - 多对一。
public class Person {
public int PersonId { get; set; }
public string Name { get; set; }
public virtual ICollection<Buy> Buys { get; set; } = new List<Buy>();
}
public class Buy {
public int BuyId { get; set; }
public int PersonId { get; set; }
public int BookId { get; set; }
public virtual Person Person { get; set; }
public virtual Book Book { get; set; }
}
public class Book {
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Buy> Buys { get; set; } = new List<Buy>();
}
有上下文。
public class MyContext : DbContext {
public DbSet<Person> People { get; set; }
public DbSet<Book> Books { get; set; }
public DbSet<Buy> Buys { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.Entity<Person>()
.Collection(c => c.Buys).InverseReference(c => c.Person)
.ForeignKey(c => c.PersonId);
modelBuilder.Entity<Book>()
.Collection(i => i.Buys).InverseReference(i => i.Book)
.ForeignKey(i => i.BookId);
}
人员 Controller - 详细信息 View 。
// _context present in given scope
public IActionResult Details(int? id) {
var person = _context.People
.Include(c => c.Buys)
.Where(c => c.PersonId == id)
.FirstOrDefault();
}
通过此配置,我希望能够从 Person 模型中获取,不仅可以获取购买信息,还可以获取相关的更多书籍。就像下面的 View 部分一样。
@model <project>.Models.Person
// (...)
@Html.DisplayFor(model => model.PersonId) // ok - person
@Html.DisplayFor(model => model.PersonName) // ok - person
@foreach (var item in Model.Buys) {
@Html.DisplayFor(modeItem => item.BuyId) // ok - buy
@Html.DisplayFor(modelItem => item.Book.Name) // null - book
}
我是否需要在 Fluent API 中编写额外的引用或进一步包含在实体模型中才能从人员级别访问项目数据?
最佳答案
您应该像添加 Buys
一样包含 Book
。我的意思是:
var person = _context.People
.Include(c => c.Buys.Select(x => x.Book))
.Where(c => c.PersonId == id)
.FirstOrDefault();
但实际上,如果您使用 MVC,最好创建包含特定 View 上所需的所有数据的 ViewModel
类,而不是在 View 上包含 EF 类。
关于asp.net - Entity Framework 7 - 访问相关实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33214521/