在Asp.net Core中使用EF Core进行内连接和将数据传递给视图模型的示例代码如下所示:
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions options) : base(options)
{
}
public DbSet Customers { get; set; }
public DbSet Orders { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection Orders { get; set; }
}
public class Order
{
public int Id { get; set; }
public string ProductName { get; set; }
public int CustomerId { get; set; }
public Customer Customer { get; set; }
}
public class CustomerViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public List OrderProducts { get; set; }
}
public class CustomerController : Controller
{
private readonly ApplicationDbContext _context;
public CustomerController(ApplicationDbContext context)
{
_context = context;
}
public IActionResult Index()
{
var customers = _context.Customers
.Include(c => c.Orders)
.Select(c => new CustomerViewModel
{
Id = c.Id,
Name = c.Name,
OrderProducts = c.Orders.Select(o => o.ProductName).ToList()
})
.ToList();
return View(customers);
}
}
@model List
@foreach (var customer in Model)
{
@customer.Name
@foreach (var product in customer.OrderProducts)
{
- @product
}
}
以上代码示例演示了如何在Asp.net Core中使用EF Core进行内连接查询,并将查询结果传递给视图模型进行显示。