简体   繁体   中英

How to select and update specific columns by Entity Framework Core?

I'm trying to convert raw SQL to EF core now. my table has many columns, such as column1 to 10, and I need to select and update specific columns. original code like this :

SELECT column1, column2 FROM table WHERE key = "someKey"

(processing data)

UPDATE table SET column2 = someValue WHERE key = "someKey"

first, I tried like this :

var query = 
  from model in context
  where key == "someKey"
  select model;

query.First().column2 = someValue;
context.SaveChanges();

this code works very fine as I wished, but SQL generated like this :

SELECT key, column1, column2, ... column10 FROM table WHERE key = "someKey"

I do not want select useless columns so I tried this:

var query = 
  from model in context
  where key == "someKey"
  select new myDTO
  {
    Item1 = model.column1,
    Item2 = model.column2
  };

query.First().Item2 = someValue;
context.SaveChanges();

this code generates SELECT SQL statement exactly I wished, but cannot generate update statement. (obviously, myDTO is not registered into DbContext) How can I do this with EF Core?

You can use Attach and Entry methods to track the changes to a entity model. To identify the model you would need all the keys (here I'm considering only one primary key: Id )

var query = 
  from model in context
  where key == "someKey"
  select new myDTO
  {
    Id = model.Id,
    Item1 = model.column1,
    Item2 = model.column2
  };

var dto = query.First();

// Here I'm using Entity but you should use the right type
var entityyModified = new Entity();
entityModified.Id = dto.Id;
entityyModified.Item1 = dto.Item1;
entityyModified.Item2 = dto.Item2;

// ...
// Item1 or Item2 properties can be assigned to different values
// ...

// Save the changes
context.Attach(entityyModified);
var dbEntry = context.Entry(entityyModified);
dbEntry.Property(e => e.Item1).IsModified = true;
dbEntry.Property(e => e.Item2).IsModified = true;
context.SaveChanges();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM