【发布时间】:2021-02-18 14:59:44
【问题描述】:
我对 EF 世界还很陌生,我想了解为什么我无法保存对我的电话记录所做的更改。我意识到我需要修改我的实体,但它似乎没有任何区别。我曾尝试使用 context.xxxx,但我收到一个错误,即未定义上下文。上下文的用途是什么?如果我更改同一用户的电话类型,我想用新信息更新记录。
电话定义:
namespace NewSMS.DATA.EF
{
using System;
using System.Collections.Generic;
public partial class Phone
{
public int Phone_ID { get; set; }
public string Phone_Number { get; set; }
public int User_PK1 { get; set; }
public int LU_Phone_Type_PK1 { get; set; }
public Nullable<bool> Available { get; set; }
public virtual LU_Phone_Type LU_Phone_Type { get; set; }
public virtual User User { get; set; }
}
}
代码:
if (phnMems != null && phnMems.Count > 0)
{
var smsPhn = new Phone { };
foreach (var item in phnMems)
{
smsPhn.Phone_Number = item.Phone_Number;
smsPhn.LU_Phone_Type_PK1 = item.Phone_Type_ID;
smsPhn.User_PK1 = obj.User_ID;
Phone phoneInfo = db.Phone.FirstOrDefault(n => n.User_PK1 == obj.User_ID);
if (phoneInfo == null)
{
db.Phone.Add(smsPhn);
db.SaveChanges();
}
else
{
smsPhn.Phone_ID = phoneInfo.Phone_ID; //keep userID
db.Entry(phoneInfo).State = EntityState.Modified;
phoneInfo = smsPhn;
db.SaveChanges();
}
}
} //End IF
【问题讨论】: