我的問題是訪問第二層關係上的Web App中的相關實體。沒有找到與EF7相關的正確答案。實體框架7 - 訪問相關實體
讓我們來看看以下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);
}
Person Controller - Details 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();
}
有了這個配置我旨在能夠從人物模型獲取,不僅收購的信息,但也涉及進一步的書籍。就像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
}
我需要用流利的API編寫額外的引用或做進一步包括在實體模型能夠從人級訪問項目的數據?
更好的做法是進行自定義模型所需的數據,並在控制器填充它,然後將它傳遞給視圖 –