使用entityframework创建插入和更新方法 [英] Creating insert and update methods using entityframework

查看:75
本文介绍了使用entityframework创建插入和更新方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有表(A),其中包含三列

一个是主键(A)(自动增量)标识,剩下两个是外键(两者都是自动增量)。

i基于主键插入和编辑(自动增量)是否正确?

如果不是如何使用实体框架编写插入和更新语句?



我尝试过: < br $>


we have table(A) with Three columns in that
one is primary key(A) (auto increment) identity and remaining two are foreign keys(both are auto increment).
i am inserting and editing based on primary key(auto increment) is it correct?
if not how to write insert and update statements using entity framework?

What I have tried:

public void InsOrUpdate(int id, int pid, int cId)
        {
            var cP = _uoW.Com.FindBy(CP => CP.Id == id).FirstOrDefault();
            if (cP != null)
            {
                cP.Id = id;
                cP.PId = pId;
                cP.CId = cId;
                _uoW.Com.Edit(cP);
            }
            else
            {
                cP=new Comp();
                cP.Id = id;
                cP.PId = pid;
                cP.CId = cId;
                _uoW.Com.Add(cP);
            }
            _uoW.SaveChanges();
        }

推荐答案

所以,你有两个选择。我对这个问题有一个提示,并且答案很可靠:

具有复合密钥支持的通用实体框架AddOrUpdate方法 [ ^ ]



现在,如果你想要的只是一张桌子的基本支持只会更新几个值,您可以执行以下操作:

So, you have a couple of options here. I have a tip on this very issue, and a robust answer:
Generic Entity Framework AddOrUpdate Method with Composite Key Support[^]

Now, if all you want is basic support for one single table that will just update a couple of values, you can do the following:
public void InsOrUpdate(int id, int pid, int cId)
        {
            var cP = _uoW.Com.Find(id); // DbSet.Find works really well
            if (cP != null) //there is no need to try and set the Id. We already have it.
            {
                cP.PId = pId;
                cP.CId = cId;
                _uoW.Entry(cP).State = EntityState.Modified; // Here's the secret sauce
            }
            else
            {
                cP=new Comp //the cool kids use object initializers
                {
                   Id = id;
                   PId = pid;
                   CId = cId;
                };
                _uoW.Entry(cP).State = EntityState.Added;
            }
            _uoW.SaveChanges();
        }


这篇关于使用entityframework创建插入和更新方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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