One to Many with Entity Framework not updating the

2019-08-03 05:56发布

问题:

I need some help, I have been searching everywhere for ages to why this keeps happening. I basically have 2 tables, Company and Address. A company can have multiple addresses. My classes and tables look like the following

TABLES:

create table Company (
    companyid int PRIMARY KEY IDENTITY not null,
    name varchar(100),
    agencyref varchar(20),
    website varchar(100),
    phoneno varchar(20),
    faxno varchar(20),
    modified datetime DEFAULT (GETDATE())   
);

create table Address (
      addressid int PRIMARY KEY IDENTITY not null,
      companyid int null, //Does the same if set to not null
        addressLine1 varchar(100),
        addressLine2 varchar(100),
        city varchar(50),
        county varchar(100),
        postcode varchar(10),
        modified datetime DEFAULT (GETDATE()),
        foreign key ( companyid ) references Company (companyid)
);

CLASSSES

public class Company
{
    [Key]
    [HiddenInput(DisplayValue = false)]
    public int companyid { get; set; }

    [DisplayName("Company Name:")]
    public string name { get; set; }

    [DisplayName("Client Reference:")]
    public string agencyref { get; set; }

    [DisplayName("Website Address:")]
    public string website { get; set; }

    [DisplayName("Phone No:")]
    public string phoneno { get; set; }

    [DisplayName("Fax No:")]
    public string faxno { get; set; }

    private DateTime _modified = DateTime.Now;
    [DataType(DataType.DateTime)]
    public DateTime modified
    {
        get { return _modified; }
        set { _modified = value; }
    }
    public virtual ICollection<Address> Address { get; set; }
}

public class Address
{
    [Key]
    [HiddenInput(DisplayValue = false)]
    public int addressid { get; set; }

    [DisplayName("Address Line 1:")]
    public string addressline1 { get; set; }

    [DisplayName("Address Line 2:")]
    public string addressline2 { get; set; }

    [DisplayName("City:")]
    public string city { get; set; }

    [DisplayName("County:")]
    public string county { get; set; }

    [DisplayName("Postcode:")]
    public string postcode { get; set; }

    private DateTime _modified = DateTime.Now;

    [DataType(DataType.DateTime)]
    public DateTime modified
    {
        get { return _modified; }
        set { _modified = value; }
    }
    public virtual Company Company { get; set; }
}

My MODEL BUILDER

modelBuilder.Entity<Company>().HasMany(c => c.Address).WithOptional(p => p.Company).Map(c => c.MapKey("companyid"));

I have been using Code First and the database is already there. the results I get from the database is:

COMPANY TABLE:

companyid   name    agencyref   website phoneno faxno   modified
4   erg NULL    NULL    NULL    NULL    2012-12-20 13:20:56.430

ADDRESS TABLE:

addressid   companyid   addressLine1    addressLine2    city    county  postcode    modified
2   NULL    hkjh    NULL    NULL    NULL    NULL    2012-12-20 13:50:37.977

As you can see I expect the companyid in Address Table to be populated with 4, but for some reason this is not doing that.

Wonder if anyone can help me solve this frustrating problem. I thought it was simple to use a view attached to a view model, that returned two classes populated with data, then insert this into the database:

My clientModel class is nice and simple:

public class ClientModel
{
    public Company Company { get; set; }
    public Address Address { get; set; }
}

MY VIEW on the controller is:

    [HttpPost]
    public ActionResult Edit(ClientModel client)
    {
       // CompanyAddress ca = new CompanyAddress();
        Domain.Data.EFDbContext context = new Domain.Data.EFDbContext();
        if (ModelState.IsValid)
        {
            context.Companies.Add(client.Company);
            context.Addresses.Add(client.Address);
            context.SaveChanges();
            return RedirectToAction("Index");
        }
        else
        {
            return View(client);
        }
    }

This is so my Edit page contains

@model TimesheetMVC.WebUI.Models.ClientModel

(enclosed within a FormMethod.Post)

<fieldset>
    <legend>Company Details</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.Company.name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Company.name)
        @Html.ValidationMessageFor(model => model.Company.name)
    </div>        
    <div class="editor-label">
        @Html.LabelFor(model => model.Company.agencyref)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Company.agencyref)
        @Html.ValidationMessageFor(model => model.Company.agencyref)
    </div>

</fieldset>
<fieldset>
    <legend>Address Details</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.Address.addressline1)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Address.addressline1)
        @Html.ValidationMessageFor(model => model.Address.addressline1)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.Address.addressline2)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Address.addressline2)
        @Html.ValidationMessageFor(model => model.Address.addressline2)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.Address.city)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Address.city)
        @Html.ValidationMessageFor(model => model.Address.city)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.Address.county)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Address.county)
        @Html.ValidationMessageFor(model => model.Address.county)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.Address.postcode)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Address.postcode)
        @Html.ValidationMessageFor(model => model.Address.postcode)
    </div>

Any help please......

回答1:

You may be saving your data incorrectly. Have you tried adding your address data to your company model, then saving just the company:

Domain.Data.EFDbContext context = new Domain.Data.EFDbContext();
if (ModelState.IsValid)
{
    client.Company.Address.Add(client.Address);
    context.Companies.Add(client.Company);
    context.SaveChanges();
    return RedirectToAction("Index");
}
else
{
    return View(client);
}

Hope that helps.