本文介绍了使用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

                       });

推荐答案

existingChild.property = value;
connection.Entrry(existingChild).State = EntityState.Modified;


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

10-29 10:27