简体   繁体   中英

Entity Framework saving data in one-to-one relation

I have two tables as following:

Table 1: ID(PK) Name

Table 2: ID(PK) Email Table1ID(FK)

I'm using Entity Framework to save data & once it is saved I retrieve it using Ajax call & display it in my view. However, the Foreign key column is not updated in the view while other data is. I have to manually refresh the web form to see updated foreign key value.

Here is some code from controller:

table2Obj = new Table2Object();
table2Obj.Email = emails;
table2Obj.Table1ID = Convert.ToInt32(ddlReferralTypes);
Context.Table2Objects.Add(table2Obj);
Context.SaveChanges();

List<Table2Object> table2Objs = Context.GetTable2Object();
string htmlView = RenderPartialViewToString("_ReferralList", table2Objs);
htmlView = HttpUtility.JavaScriptStringEncode(htmlView);
return Content("{\"MessageType\":\"success\",\"MessageContent\":\"Referral added successfully\",\"htmlPartialView\":\"" + htmlView + "\"}");

This is how view looks like:

    @model List<MyModels.Models.Table2Object>
    @foreach (var item in Model)
    {
    //display data
Email: @Html.DisplayFor(modelItem => item.Email)
Referral: @Html.DisplayFor(modelItem => item.Table2.Name)
    }

Have you tried using the .Include() method? I think in your case it would be:

this.Table2Objects.Include("Email").ToList();

Or

this.Table2Objects.Include(t => t.Email).ToList();

Hopefully that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM