Anarion
Anarion

Reputation: 2534

EF Core - Ignore field (do not create a column in db) but fill it from raw query

I have an entity with a field that should not be created in the database, but should be filled from a stored procedure.

public class Item 
{
    public int Id {get; set;}
    public int CalculatedField {get; set;}
}

Then I want to fill it with a stored procedure

var items = _db.Items.FromSqlRaw("select * from StoredProcedure()").ToList()

But if I use [NotMapped] attribute or .Ignore fluent option - the EF the field completely, and even though my stored procedure returns CalculatedField, EF does not use it.

Is there any way to achieve this behavior?

Upvotes: 2

Views: 692

Answers (1)

devlin carnate
devlin carnate

Reputation: 8622

You can use the query results to assign the value. There are various ways in which to do that. Here's one, where you iterate over the query results and instantiate an Item, assign property values and add it to a list of Items:

var items = new List<Item>();
var results = _db.Items.FromSqlRaw("select * from StoredProcedure()").ToList();
foreach(var result in results) {
   var item = new Item {
      Id = result.Id,
      CalculatedField = result.CalculatedField
   }
   items.Add(item);
}

Upvotes: 1

Related Questions