Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform a generic insert in entity framework?

I want to perform a generic insert in entity framework. This is what I wrote -

static public void Insert<T>(MyEntities DataContext, T obj) where T : class
        {
            try
            {
                DataContext.AddObject(DataContext,obj);
                DataContext.SaveChanges();
            }
            catch (Exception e)
            {
                throw new Exception("Problems adding object" + e);
            }
        }

But as you can see the AddObject method is not what i want...it gives exception as it expects an enitysetname I want to pass in the object and then add that object to my database. But I cannot do AddtoObjectName() as I dont know the object. Can anyone point me in the right direction here..

like image 444
Vishal Avatar asked Jun 03 '26 10:06

Vishal


1 Answers

In EF 4 you can do:

var os = DataContext.CreateObjectSet<T>();
os.AddObject(obj);
DataContext.SaveChanges();

And please remove the stack-eating try/catch.

like image 74
Craig Stuntz Avatar answered Jun 06 '26 07:06

Craig Stuntz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!