开发者

C# Entitity framework SaveChanges() not working

开发者 https://www.devze.com 2023-02-17 03:08 出处:网络
After running this code I find no entrys in my database. I receive no errors from the code. Does anyone know what I mite be doing wrong ?

After running this code I find no entrys in my database. I receive no errors from the code.

Does anyone know what I mite be doing wrong ?

PeopleEntities1 db = new PeopleEntities1();


            Person roger = new Person() 
            {  
                age = 25,
                firstname = "Roger", 
                lastname = "Rabbit", 
                location = "Canada", 
                job开发者_如何转开发 = "freelance", 


            };

            db.AddToPeople(roger);
            db.SaveChanges(true);


What is the location of your database? Make sure you are not you're copying it to your output directory everytime you run your code. I might have had a similar issue with an SQLite database which was copied to the output directory every time I run my application, which made me lose changes I had made during the previous run


Instead of db.AddToPeople(), try db.People.Add().

Also, wrap a using statement around the db variable to make sure the context and connection get disposed correctly.

This is for EF4 and .NET 4.0.

Assuming you have a list called People setup.

Hope this helps! :)

Here is the code:

using (PeopleEntities1 db = new PeopleEntities1())
{


            Person roger = new Person() 
            {  
                age = 25,
                firstname = "Roger", 
                lastname = "Rabbit", 
                location = "Canada", 
                job = "freelance", 


            };

            db.People.Add(roger);
            db.SaveChanges(true);
}


First of all, SaveChanges(true) is an obsolete method so I wouldn't recommend using it. Have you tried just using SaveChanges() ? Like in db.SaveChanges()

The closest method to SaveChanges(boolean) is SaveChanges(SaveOptions) which Persists all updates to the data source with the specified SaveOptions.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号