.Net Knowledge Book : Web Development with Asp.Net MVC and Entity Framework by Desjardins Patrick

.Net Knowledge Book : Web Development with Asp.Net MVC and Entity Framework by Desjardins Patrick

Author:Desjardins, Patrick
Language: eng
Format: epub
Publisher: UNKNOWN
Published: 2016-12-30T16:00:00+00:00


Release Date: 19-Jun-13

Url: http://patrickdesjardins.com/blog/?post_type=post&p=1888

In some scenarios you will want to update a specific property but not others. This can be for security reasons or for performance reasons. In either case, the goal is to update only a specific property of your entity. In Entity Framework, this can be done by specifying to the database context (dbcontext) the property status. Each property does have an IsModified property that can be set to true or false.

context.Entry(yourObject).Property(u => u.YourProperty).IsModified = true;

Of course, if your object is from view, this is not known by Entity Framework’s database context and will require attaching it first.

using (var entities = new MyDbContext())

{

var entity = new YourEntity { Id = id, Name = "Test" };

entities.YourEntities.Attach(entity);

entities.Entry(entity).Property(e => e.Name).IsModified = true;

entities.SaveChanges();

}

This will save YourEntity entity but only change the Name property. This is quite useful in scenarios where you do not want the user to hack a web form to add properties that you don’t want to be read by Entity Framework. By specifying which property is modified, you tell Entity Framework to generate the SQL with only the “Set” for them. For example:

UPDATE YourEntitySET Name = "Test"WHERE Id = 123;

Finally, you may want to close the automatic validation if you are using the validation mechanism. This can be done by setting the ValidateOnSaveEnabled to false.

entities.Configuration.ValidateOnSaveEnabled = false;

The reason is that since not all the objects are loaded, you may have some validations on field that should be required that are not done at this time. To temporarily disable the validation, use ValidateOnSaveEnabled. Of course, set it back to true once the save changes is done.

Entity Framework and conversion of a datetime2



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.