asp.net使用EntityFramework在html中显示连接表

时间:2015-12-08 15:09:43

标签: c# sql asp.net entity-framework join

我完成了这个asp.net tutorial

最后,我有2个带2个脚手架的模型。

模特作者

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace ContosoBooks.Models
{
    public class Author
    {
        [ScaffoldColumn(false)]
        public int AuthorID { get; set; }
        [Required]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }

        [Display(Name = "First Name")]
        public string FirstMidName { get; set; }

        public virtual ICollection<Book> Books { get; set; }
    }
}

模特书

using System.ComponentModel.DataAnnotations;

namespace ContosoBooks.Models
{
    public class Book
    {
        [ScaffoldColumn(false)]
        public int BookID { get; set; }
        [Required]
        public string Title { get; set; }

        public int Year { get; set; }
        [Range(1, 500)]
        public decimal Price { get; set; }

        public string Genre { get; set; }

        [ScaffoldColumn(false)]
        public int AuthorID { get; set; }

        // Navigation property
        public virtual Author Author { get; set; }
    }
}

现在我想通过AuthorID加入这两个表,只需在主视图中显示我的一个合并表。

最简单的方法是什么?

1 个答案:

答案 0 :(得分:0)

一种选择是使用LINQ连接这两个模型类,以将合并的Result转换为名为mergedResultViewModel的自定义View Model对象列表。以下代码中的TestDBContext是EF的dbContext。

var query = from au in TestDBContext.Authors join bk in TestDBContext.Books on au.AuthorID equals bk.AuthorID
    select new MergedResultViewModel { au.AuthorID, au.FirstMidName, bk.BookID, bk.Title, bk.Year, bk.Price, bk.Genre }

var mergedResultViewModel = query.ToList();

MergedResultViewModel类型可以在代码文件中定义如下。

public class MergedResultViewModel
    {
        public int AuthorID { get; set; }
        public string FirstMidName { get; set; }
        public int BookID { get; set; }
        public string Title { get; set; }
        public int Year { get; set; }
        public decimal Price { get; set; }
        public string Genre { get; set; }
    }