更新MVC实体框架中的多个列

时间:2018-01-14 14:40:53

标签: entity-framework

我的桌子里面有超过25个字段。它有一些包含大量数据的列(nvarchar(MAX))。它有用户表格,如:

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

现在我只需更新其中的名称,邮件,联系人字段。

我经历了几个帖子,例如update 1 fieldupdate multiple fields。 但是这些需要为该特定用户ID加载数据,然后像下面那样更新它:

 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;
    }

有没有更好的方法不需要加载整个数据?

3 个答案:

答案 0 :(得分:1)

您可以按照以下方法更新表格中的少数字段。

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));

答案 1 :(得分:1)

如果您需要EFish方法(无SQL语句),可以使用Entity Framework ExtensionsUPDATE视为批处理语句,现在重新标记为Entity Framework plus

我使用的是旧版本,但这个版本的工作方式似乎相似。对于您的特定情况:

dc.Users.Where(u => 
    u.ID = userID)
    .Update(x => new User() 
          { 
              Name = name, 
              Mail = mail, 
              Contact = contact
          });

AFAIK,这将直接针对数据库发出UPDATE(默认情况下,它不包含在事务中)。但是,可以在需要时使用自定义事务(即TransactionScope`)。

答案 2 :(得分:0)

将存储过程添加到数据库以更新表中的几个字段。您可以使用实体框架来调用存储过程来更新数据库中的字段

其中一篇文章应该有所帮助

http://www.entityframeworktutorial.net/stored-procedure-in-entity-framework.aspx

https://www.mikesdotnetting.com/article/299/entity-framework-code-first-and-stored-procedures