M
M
Matsun2017-03-11 12:40:37
ASP.NET
Matsun, 2017-03-11 12:40:37

How to modify only one element field using Entity Framework?

There is a method

public void IncreaseArticleViews(int ArticleId)
        {
            context.Articles.FirstOrDefault(p => p.ArticleId == ArticleId).CountViews += 1;
            context.SaveChanges();
        }

There is a task - to modify only one property of the article - it is necessary to increase the number of views of articles CountViews by one.
The problem is that this method not only saves the updated CountViews property to the database, but all the rest.
How can I update only one cell in the database? I don't download the entire line.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anvar Shakhmaev, 2017-03-11
@Matsu

var article = context.Articles.FirstOrDefault(p => p.ArticleId == ArticleId);
int countViews = article.newCountViews++;
context.Database.ExecuteSqlCommand("UPDATE dbo.Articles SET CountViews = {0} WHERE ArticleId = {1}", countViews , ArticleId);

N
Newred, 2017-04-22
@Newred

I would supplement the answer from Anvar Shakhmaev @pro100gram
Why do we need to download the entire object from the database, download only the counter)
Instead of:
I would make:

var article = context.Articles.FirstOrDefault(p => p.ArticleId == ArticleId).Select(p => p.CountViews);
int countViews = article++;
context.Database.ExecuteSqlCommand("UPDATE dbo.Articles SET CountViews = {0} WHERE ArticleId = {1}", countViews , ArticleId);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question