I have table with more than 25 Fields in it. It has some column with huge data (nvarchar(MAX)). It has User table like :
ID // Primary key
Name
Mail
Contact
RegFees
.
.
. // about 25 Fields
Narration // Nvarchar(Max) may have upto 10000 chars
Tag // Nvarchar(Max) may have upto 15000 chars
Now i have to update only Name,Mail,Contact fields in it.
I have gone through several so posts like update 1 field, update multiple fields. But these require data to be loaded for that specific user ID and then Update it like :
var u = dc.Users.Where(a =>a.ID.Equals(i.ID)).FirstOrDefault();
if (u != null)
{
// Note : ALL the data of 25+ columns is loaded including nvarchar(Max)
// it will decrease performance as Whole Data is loaded first.
u.Name = i.Name;
u.Mail = i.Mail;
u.Contact = i.Contact;
}
is there any better way that does not require to load entire data ?
You can follow the below approach for updating few fields in a table.
dc.Database.ExecuteSqlCommand("Update [User] Set Name = @Name, Mail = @Mail, Contact = @Contact Where ID = @ID", new SqlParameter("@Name", "YourName"), new SqlParameter("@Mail", "newMail"), new SqlParameter("@Contact", "newContact"), new SqlParameter("@ID", 1));
If you want a EFish approach (no SQL statement) you can treat your UPDATE as a batch statement using Entity Framework Extensions, now re-branded Entity Framework plus.
I have used the old version, but the one seems to work similarly. For your particular case:
dc.Users.Where(u =>
u.ID = userID)
.Update(x => new User()
{
Name = name,
Mail = mail,
Contact = contact
});
AFAIK, this will directly issue an UPDATE against the database (it is not included in the transaction by default). However, a custom transaction (i.e. TransactionScope`) can be used when needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With