9

我是实体框架的新手。我正在尝试更新记录并将更改保存到数据库。

public void SaveEdit(Gate gate)
        {
            try
            {
                using (dc = new GateEntities())
                {
                    var query = (from tbsite in dc.tblSites
                                 where tbsite.ID == gate.ID
                                 select tbsite).FirstOrDefault();

                    query.CalledInAt = gate.CalledInAt;
                    query.CallerRequest = gate.CallerRequest;
                    query.ContactPersonOnSite = gate.ContactPersonOnSite;
                    query.Email = gate.Email;
                    query.EmailSitePerson = gate.EmailSitePerson;

                    dc.SaveChanges();
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }



        }

它不会收到异常或错误消息,但不会将更改保存到数据库。为什么它不更新记录?

4

3 回答 3

14

修改query对象之后您应该Modified在调用之前将其状态更改为context.SaveChanges()。您的上下文对象应该知道您修改的实体。假设dc是您的上下文对象:

query.CalledInAt = gate.CalledInAt;
//change other properties ..
dc.Entry(query).State = EntityState.Modified;
dc.SaveChanges();

那应该对你有用。

于 2013-09-19T08:51:47.473 回答
5

您必须使用实体框架来选择您的对象,结果对象将是可跟踪的,所以试试这个

            using (var dc = new GateEntities())
            {
                var gate = dc.tblSites.Where(g => g.ID == date.ID).FirstOrDefault();

                gate.CalledInAt = gate.CalledInAt;
                gate.CallerRequest = gate.CallerRequest;
                gate.ContactPersonOnSite = gate.ContactPersonOnSite;
                gate.Email = gate.Email;
                gate.EmailSitePerson = gate.EmailSitePerson;

                dc.SaveChanges();
            }
于 2013-09-19T04:55:13.683 回答
0

还注意到当实体没有配置主键时会发生这种情况。在 EF Core 检查您的 OnModelCreating 并确保 entity.HasKey(e => e.TheKey); 存在。

根据文档,您不需要使用状态:https ://docs.microsoft.com/en-us/ef/core/get-started/?tabs=netcore-cli

var yourEntity = await context.FirstOrDefaultAsync(e => e.Id = 1);//You can also call FindAsync(id)
yourEntity.Name = "NewName";//This line will let EF Core knows the entity has been modify
await context.SaveChangesAsync();

虽然您可以在这里查看如何使用状态:https ://docs.microsoft.com/en-us/ef/ef6/saving/change-tracking/entity-state 并且代码将如下所示:

var yourEntity = await context.FirstOrDefaultAsync(e => e.Id = 1);
yourEntity.Name = "NewName";
context.Entry(yourEntity).State = EntityState.Modified;
await context.SaveChangesAsync();

它们都是相同的,老实说,我更喜欢手动设置状态(在大型项目中),有时 EF Core 会丢失对某些实体的跟踪(这是个人经验),所以我仔细检查将状态更新为已添加或已修改。谢谢

于 2020-07-24T17:32:00.043 回答