Entity Framework 6: Clone object except ID

前端 未结 5 1083
旧时难觅i
旧时难觅i 2020-12-01 04:48

In my MVVM program I have a Model class (say MyModel) from which I have an instance of reading from the database (using Entity Framework). When retrieving the o

5条回答
  •  悲&欢浪女
    2020-12-01 05:38

    I noticed that there is no need for copying. Apparently when adding an instance of a model to the database (even if the ID is set to one that already exists in the database), Entity Framework inserts a new row in the database and auto-increments it's primary key. So this functionality is already built-in into EF. I didn't know this, sorry.
    Just for clarity's sake here is an example:

    using(var database = new MyDbContext()) {
        MyModel myModel = database.FirstOrDefault(m => m.SomeProperty == someValue);
        myModel.SomeOtherProperty = someOtherValue; //user changed a value
        database.MyModels.Add(myModel); //even though the ID of myModel exists in the database, it gets added as a new row and the ID gets auto-incremented 
        database.SaveChanges();
    }
    

提交回复
热议问题