插入具有一对多关系的新实体,而不是在两个表

时间:2015-11-28 15:05:08

标签: c# entity-framework asp.net-mvc-5

我使用MVC5和EF6 Code First来创建一个可以拥有多个Company实体的新Contact实体。但是,只有Company记录正在写入数据库。

型号:

public class Company
{
    public virtual int CompanyId { get; set; }

    [Required]
    public virtual string Name { get; set; }

    [Required]
    public virtual Address Address { get; set; }

    [Required]
    public virtual string Phone { get; set; }

    public virtual string Email { get; set; }

    // can have many Contacts
    public virtual IEnumerable<Contact> Contacts { get; set; }
}

public class Contact
{
    public virtual int ContactId { get; set; }

    [Required]
    public virtual string Title { get; set; }

    [Required]
    public virtual string Forename { get; set; }

    [Required]
    public virtual string Surname { get; set; }

    [Required]
    public virtual string Phone { get; set; }

    public virtual string Email { get; set; }

    // belongs to one Company
    public virtual Company Company { get; set; }
}

控制器:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create_POST([Bind(Include = "CallerType,Name,Address,Phone,Email,Contacts")] CompanyViewModel viewModel)
    {
        if (ModelState.IsValid)
        {
            // tried commented code to make sure it wasn't a problem with my repository and contact records aren't saved to database...

            //var context = new EfDbContext();

            //var company = new Company
            //{
            //    Name = viewModel.Name,
            //    Phone = viewModel.Phone,
            //    Address = viewModel.Address,
            //    Email = viewModel.Email
            //};

            //context.Companies.Add(company);

            //var contact = new Contact
            //{
            //    Company = company,
            //    Title = "mr",
            //    Forename= "f",
            //    Surname = "s",
            //    Phone = "132"
            //};

            //var contact2 = new Contact
            //{
            //    Company = company,
            //    Title = "mr",
            //    Forename = "for",
            //    Surname = "sur",
            //    Phone = "987"
            //};

            //var contacts = new List<Contact> {contact, contact2};

            //company.Contacts = contacts;

            //context.SaveChanges();


            var contacts = viewModel.Contacts.Select(c => new Contact
            {
                Title = c.Title,
                Forename = c.Forename,
                Surname = c.Surname,
                Phone = c.Phone,
                Email = c.Email
            });

            var company = new Company
            {
                Name = viewModel.Name,
                Phone = viewModel.Phone,
                Address = viewModel.Address,
                Email = viewModel.Email,
                Contacts = contacts
            };

            await _companyRepository.CreateAsync(company);

            var redirectUrl = new UrlHelper(Request.RequestContext).Action("Create", "Enquiry", new { id = company.CompanyId, callerType = viewModel.CallerType });
            return Json(new { Url = redirectUrl });
        }

        Response.StatusCode = 400;

        return PartialView("~/Views/Company/_Create.cshtml", viewModel);
    }

存储库:

    public async Task<TEntity> CreateAsync(TEntity entity)
    {
        if (entity == null) throw new ArgumentNullException(nameof(entity));
        DbContext.Set<TEntity>().Add(entity);
        await DbContext.SaveChangesAsync();
        return entity;
    }

我的印象是DbContext会知道&#39;由于它的Contacts集合已填充,因此会创建链接到已创建Contact的{​​{1}}条记录。 或者我必须创建一个Company,因为这是包含外键的表格,EF将会知道&#39;首先创建Contact

或者是否有必要先使用Company实际保存Company实体,然后将其分配到SaveChanges()条记录并执行第二次Contact? 如果是这种情况,那么我需要使用SaveChanges()吗?

对此的任何指导都会很棒,因为这是我第一次使用Entity Framework。

2 个答案:

答案 0 :(得分:3)

Contacts必须是ICollection。 EF不支持IEnumerable作为导航属性,因为无法向其添加项目。

这也意味着您应该更改创建contacts的代码:

var contacts = viewModel.Contacts.Select(c => new Contact
{
    Title = c.Title,
    Forename = c.Forename,
    Surname = c.Surname,
    Phone = c.Phone,
    Email = c.Email
}).ToList();  // <= ToList() added

答案 1 :(得分:1)

您的关系应该通过覆盖OnModelCreating方法在DbContext中设置

我自己是Entity Framework的新手,但发现方法名称有助于学习如何建立关系

希望以下内容可以提供帮助

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Company>()
                    .HasMany(c => c.Contacts)
                    .WithRequired(co => co.Company)
                    .HasForeignKey(co => co.CompanyId);
}

您还可以在关系中设置级联,这样当删除一个实体时,相关实体也会被删除,如果您需要删除公司,可能需要考虑这些实体