实体框架多对多关系,无法传递模型

时间:2018-05-16 18:14:07

标签: c# asp.net entity-framework

我正在使用内置的CRUD脚手架,在两个模型“站点”和“员工”之间存在多对多关系。我正在使用“DataOwner”模型来桥接这两者。最终目标是能够创建新站点并将一个或多个Employees指定为该站点的DataOwners。我在调试时一直在关注每一行,看起来所有内容都是正确的,但是当我尝试查看它时,它总是缺少Employee模型。 (Employee = null)。

site.DataOwners.Employees = null,但EmployeeId(int),Site(Model)和SiteId(int)都很好。

详细说明:

public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var site = await _context.Sites
                    .Include(s => s.DataOwners)
                    .AsNoTracking()
                    .SingleOrDefaultAsync(m => m.SiteId == id);
            if (site == null)
            {
                return NotFound();
            }

            return View(site);
        }

创建:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("SiteId,SiteCode,DataOwners")]Site site, int[] dataOwnersById)
    {
        if (ModelState.IsValid)
        {
            if (dataOwnersById != null)
            {

                site.DataOwners = new List<DataOwner>();

                foreach (var item in dataOwnersById)
                {
                    var employee = _context.Employees.FirstOrDefault(e => e.EmployeeId == item);
                    var dataOwnerAdd = new DataOwner() { SiteId = site.SiteId, EmployeeId = item, Employee = employee };
                    site.DataOwners.Add(dataOwnerAdd);
                }
            }

            _context.Add(site);
            await _context.SaveChangesAsync();

            return RedirectToAction(nameof(Index));
        }
        ViewData["DataOwner"] = new MultiSelectList(_context.Employees, "EmployeeId", "FullName");
        return View(site);
    }

    // GET: Sites/Edit/5
    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var site = await _context.Sites.SingleOrDefaultAsync(m => m.SiteId == id);
        if (site == null)
        {
            return NotFound();
        }
        return View(site);
    }

员工模式:

namespace Demo.Models
{
    public class Employee
    {
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int EmployeeId { get; set; }
        [Display(Name = "First Name"), StringLength(50), MinLength(3)]
        public string FirstName { get; set; }
        [Display(Name = "First Name"), StringLength(50), MinLength(3)]
        public string LastName { get; set; }
        public string FullName => LastName + ", " + FirstName;

        public ICollection<DataOwner> DataOwners { get; set; }
    }
}

网站模型:

namespace Demo.Models
{
    public class Site
    {
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int SiteId { get; set; }
        [Display(Name = "Site Code"), StringLength(50), MinLength(1)]
        public string SiteCode { get; set; }

        public ICollection<DataOwner> DataOwners { get; set; }
    }
}

DataOwner模型:

namespace Demo.Models
{
    public class DataOwner
    {
        public int EmployeeId { get; set; }
        public Employee Employee { get; set; }
        public int SiteId { get; set; }
        public Site Site { get; set; }
    }
}

的DbContext:

namespace Demo.Data
{
    public class DemoContext : DbContext
    {
        public DemoContext(DbContextOptions<DemoContext> options) : base(options)
        {
        }

        public DbSet<Site> Sites { get; set; }
        public DbSet<Employee> Employees { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<DataOwner>()
                .HasKey(d => new {d.EmployeeId, d.SiteId});
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您还需要包含DataOwner.Employee数据:

var site = await _context.Sites
                         .Include(s => s.DataOwners)
                             .ThenInclude(d => d.Employee)
                         .AsNoTracking()
                         .SingleOrDefaultAsync(m => m.SiteId == id);