asp.net - Entity Framework 7 - 访问相关实体

标签 asp.net asp.net-mvc entity-framework asp.net-mvc-5 entity-framework-core

我的问题是访问 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/

相关文章:

c# - 当我们在设计器中指定列时,如何填充gridview?

c# - 根据 Access 表检查 ID 并循环执行 SQL 语句

asp.net-mvc - 如何在 MVC 5 中将多个路由设置为同一操作方法?

c# - Entity Framework Code First 中的日期比较帮助

entity-framework - 带有 Entity Framework 的 Azure 函数

c# - Log4Net 的附加组件

javascript - 如何在MVC4的UI中使用jQuery创建DataTable?

c# - 意外的模型绑定(bind)

javascript - LazyLoadingEnabled = true 通过 AJAX 从 EF 返回不正确的数组

asp.net - 从浏览器到 IIS 的并发连接