Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
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:

C#
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();
        }
Posted
Updated 8-Sep-16 6:17am
v3
Comments
Maciej Los 8-Sep-16 10:59am    
Does it working? If yes, it is correct insert/edit statement for entity framework.
;)
Vincent Maverick Durano 8-Sep-16 15:32pm    
perhaps this would help: http://www.c-sharpcorner.com/article/entity-framework-basic-guide-to-perform-fetch-filter-insert-update-and-dele/

1 solution

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:
C#
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();
        }
 
Share this answer
 
Comments
Karthik_Mahalingam 9-Sep-16 1:11am    
5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900