C# asp.net使用EntityFramework在html中显示联接表
我完成了这个 最后,我有2个模型和2个脚手架项目 模范作家C# asp.net使用EntityFramework在html中显示联接表,c#,sql,asp.net,entity-framework,join,C#,Sql,Asp.net,Entity Framework,Join,我完成了这个 最后,我有2个模型和2个脚手架项目 模范作家 using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace ContosoBooks.Models { public class Author { [ScaffoldColumn(false)] public int AuthorID { get; set; }
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; }
}
}
现在我想通过authord连接这两个表,并在主视图中简单地显示我的一个合并表
最简单的方法是什么?一个选项是使用LINQ连接这两个模型类,以将合并结果获取到名为mergedResultViewModel的自定义视图模型对象列表中。下面代码中的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; }
}
好的,那么我如何在html视图中显示mergedResult呢?我更新了答案。假设您使用的是MVC,一旦有了mergedResultViewModel(这是自定义对象mergedResultViewModel的列表),就可以使用它使用脚手架创建MVC列表视图。您能为我发布所有mergedResultViewModel.cs文件吗?添加了代码来定义ViewModel的类
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; }
}