首页 > 解决方案 > 如何创建具有多个查询的实体

问题描述

我有一个数据库优先的实体框架模型。在数据库中有一个矩阵行表,我的应用程序应该在其上显示和执行 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 表?

标签: c#entity-framework-6

解决方案


看到这个:

 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

推荐阅读