简体   繁体   English

插入具有一对多关系的新实体,而不在两个表中都创建记录

[英]Insert new Entity with one to many relationship not creating records in both tables

I'm using MVC5 and EF6 Code First to create a new Company entity that can have many Contact entities. 我正在使用MVC5和EF6 Code First创建一个可以具有许多Contact实体的新Company实体。 However, only the Company record is being written to the database. 但是,只有Company记录被写入数据库。

Models: 楷模:

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; }
}

Controller: 控制器:

    [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);
    }

Repository: 仓库:

    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;
    }

I was under the impression that the DbContext would 'know' that because it's Contacts collection is populated it would create Contact records that link to the created Company . 我的印象是DbContext会“知道”,因为填充了Contacts集合,它将创建链接到创建的Company Contact记录。 Or do I have to create a Contact instead as this is the table with the foreign key in it and EF will 'know' to create the Company first? 还是我必须创建Contact因为这是其中包含外键的表,EF会“知道”首先创建Company吗?

Or is it necessary to actually save the Company entity first using SaveChanges() and then assign it to the Contact records and perform a second SaveChanges() ? 还是需要首先使用SaveChanges()实际保存Company实体,然后将其分配给Contact记录并执行第二个SaveChanges()
If this is the case then would I need to use Database.BeginTransaction() ? 如果是这种情况,那么我需要使用Database.BeginTransaction()吗?

Any guidance on this would be great as this is my first time using Entity Framework. 关于这方面的任何指导都将是很棒的,因为这是我第一次使用实体框架。

Contacts must be an ICollection . Contacts必须是ICollection EF doesn't support IEnumerable as navigation properties, because it's impossible to add items to them. EF不支持将IEnumerable用作导航属性,因为无法向其中添加项目。

This also means that you should change the code that creates contacts : 这也意味着您应该更改创建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

Your relationships should be set up within your DbContext by overriding the OnModelCreating method 您的关系应通过覆盖OnModelCreating方法在DbContext中建立

I'm new to Entity Framework myself, but found that the methods names aid in learning how to set up relationships 我本人是Entity Framework的新手,但发现方法名称有助于学习如何建立关系

Hopefully the below can help 希望以下内容能对您有所帮助

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

You can also set up cascading within your relationship, so that when one entity is removed, the related entities are also deleted, which may be something to consider if you ever need to delete a Company 您还可以在您的关系中设置级联,这样,当删除一个实体时,相关实体也将被删除,如果您需要删除公司,可能需要考虑这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 EF Core,一对多关系 - 如何使用单个视图在两个表中插入记录? - EF Core, one-to-many relationship - how to insert records in both tables with a single view? 为什么 Entity Framework Core 试图将记录从多对多关系而不是连接表插入到其中一个表中? - Why is Entity Framework Core attempting to insert records into one of the tables from many to many relationships and NOT the join table? 将批量数据插入到具有一对多关系的表中 - Insert bulk data into tables that are in a one to many relationship 如何使用实体框架在WPF c#中的两个表之间插​​入一对多关系的数据? - How to insert data for one to many relationship between two tables in WPF c# using Entity Framework? 使用Entity Framework和MVC将记录插入具有主/从关系的表中 - Insert records into tables with master/detail relationship with Entity Framework and MVC 多对多关系-实体框架正在创建新对象 - Many to Many Relationship - Entity Framework is creating new objects 多对多关系实体框架创建新行 - Many to Many relationship Entity Framework creating new rows 将两个具有FK关系的表插入到一个UoW中? - Insert both two tables with FK relationship in one UoW? 实体框架更新一对一关系的两个表 - Entity Framework updating two tables with one to many relationship 在具有一对多关系的实体中同时插入数据 - Insert data simultaneously in entity having one to many relationship
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM