使用entityframework时,“设置值”不会更新现有行。 [英] Updating existing rows is not working by 'set values' when using entityframework.

查看:67
本文介绍了使用entityframework时,“设置值”不会更新现有行。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么setvalues对我不起作用?它对模型对象不起作用吗?





Why setvalues is not working for me? Does it not work for model objects?


using (var connection = new TReportEntitiesConnection())
        {

            var header = connection.THeaders.Include("TReports").SingleOrDefault(f => f.ID == model.ID);

            if (header != null)
            {
                header.THeaderTitle = model.THeaderTitle; //update parent
            }
            foreach (var existingChild in header.TReports.ToList())
            {

                if (!model.TReports.Any(c => c.ID == existingChild.ID))
                    connection.TReport.Remove(existingChild);

            }
            foreach (var url in model.TReports)
            {
                var existingChild = header.TReports
                    .Where(c => c.ID == url.ID)
                    .SingleOrDefault();


                if (existingChild!= null)
                { //update child
                    connection.Entry(existingChild).CurrentValues.SetValues(url);
                }
                else
                {
                    var newChild = new TReport
                    {
                        TReportName = url.name,
                        URL = url.url,
                    };

                    header.TReports.Add(newChild);
                }
            }
            connection.SaveChanges();
        }





我尝试过:



我尝试将其更改为但后来我意识到它不断添加新行。



What I have tried:

I tried changing it to but then I realized it is keep adding new rows.

header.TReports.Add(new TReport()
                       {
                           TReportName=url.name,
                           URL=url.url

                       });

推荐答案

如何让它更容易。不要使用SetValues,只需设置要更改的属性的值。

How about making it easier. Don't use SetValues, instead, just set the value of the property you want to change.
existingChild.property = value;
connection.Entrry(existingChild).State = EntityState.Modified;


这篇关于使用entityframework时,“设置值”不会更新现有行。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆