实体框架一对多不更新外键 [英] One to Many with Entity Framework not updating the foreign key

查看:93
本文介绍了实体框架一对多不更新外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助,我一直在寻找可以解决这种情况的原因.我基本上有2个表,公司和地址.一个公司可以有多个地址.我的类和表如下所示

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

表格:

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

课程

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

我的模型建造者

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

我一直在使用Code First,并且数据库已经存在.我从数据库中得到的结果是:

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

公司表格:

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

地址表:

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

如您所见,我希望地址表中的公司ID填充4,但由于某种原因,它没有这样做.

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:

我的clientModel类很简单:

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

(包含在FormMethod.Post中)

(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>

请帮助...

推荐答案

您可能不正确地保存了数据.您是否尝试过将地址数据添加到公司模型中,然后仅保存公司:

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

希望有帮助.

这篇关于实体框架一对多不更新外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆