我有一个数据库优先的实体框架模型。 在数据库中,有一个矩阵行的表,我的应用程序应该在该表上显示并执行CRUD操作。 为了简单起见,我想创建一个实体来跟踪一组特定的值,并对数据库进行更改。 我可以将此实体连接到数据库,以便它跟踪我所做的每个更改吗?
以下实体接受值列表,并将其转换为平面对象。最终,我想更改构造函数以直接访问数据库(给了更多参数),然后能够在保存时更新每个属性的特定值。
这是我的示例实体:
public class ServiceAdjustment
{
public string UNIT { get; set; }
public string INFIND { get; set; }
public string VASTREET { get; set; }
public string VALNOSTR { get; set; }
public string VALSEWER { get; set; }
public string VALWATER { get; set; }
public string VALCURB { get; set; }
public string VALSWK { get; set; }
public string STSZ { get; set; }
public string STLSM { get; set; }
public string STND_DPT { get; set; }
public string VALDELTA { get; set; }
public string VALNABLA { get; set; }
//constructor
public ServiceAdjustment(List<LANDADJT> landadjts)
{
UNIT = landadjts.Where(x => x.TABLE_NAME == "UNIT").Select(x => x.CODE).FirstOrDefault<string>();
INFIND = landadjts.Where(x => x.TABLE_NAME == "INFIND").Select(x => x.CODE).FirstOrDefault<string>();
VASTREET = landadjts.Where(x => x.TABLE_NAME == "VASTREET").Select(x => x.CODE).FirstOrDefault<string>();
VALNOSTR = landadjts.Where(x => x.TABLE_NAME == "VALNOSTR").Select(x => x.CODE).FirstOrDefault<string>();
VALSEWER = landadjts.Where(x => x.TABLE_NAME == "VALSEWER").Select(x => x.CODE).FirstOrDefault<string>();
VALWATER = landadjts.Where(x => x.TABLE_NAME == "VALWATER").Select(x => x.CODE).FirstOrDefault<string>();
VALCURB = landadjts.Where(x => x.TABLE_NAME == "VALCURB").Select(x => x.CODE).FirstOrDefault<string>();
VALSWK = landadjts.Where(x => x.TABLE_NAME == "VALSWK").Select(x => x.CODE).FirstOrDefault<string>();
STSZ = landadjts.Where(x => x.TABLE_NAME == "STSZ").Select(x => x.CODE).FirstOrDefault<string>();
STLSM = landadjts.Where(x => x.TABLE_NAME == "STLSM").Select(x => x.CODE).FirstOrDefault<string>();
STND_DPT = landadjts.Where(x => x.TABLE_NAME == "STND_DPT").Select(x => x.CODE).FirstOrDefault<string>();
VALDELTA = landadjts.Where(x => x.TABLE_NAME == "VALDELTA").Select(x => x.CODE).FirstOrDefault<string>();
VALNABLA = landadjts.Where(x => x.TABLE_NAME == "VALNABLA").Select(x => x.CODE).FirstOrDefault<string>();
}
}
如何将其连接到数据库,以便在对UNIT属性进行保存时更新在LANDADJT表中与其相关的值?
答案 0 :(得分:0)
查看此内容:
dbcontext.YourEntity.Add(new ServiceAdjustment(<yourlandadjtsVariableHere>));
dbContext.SaveChanges();
如果您需要跟踪实体,可以使用
var entity = new YourEntityClass();
var entity.PrimaryKeyColumn = 1234;
context.YourDbSet.Attach(entity);
现在您的实体已附加到ChangeTracker
。现在,您可以更改任何值并保存
entity.SomeProp = "John Doe";
dbContext.SaveChanges();
您可以通过以下方式检查实体的状态
dbContext.Entry(entity).State