ant
ant

Reputation: 1137

Including ignored string property

My db model has string property "Description", which I don't want to load each operation. So I marked it with [NotMapped] attribute. But I have one place in code, where I need this data. I tried to load it with .Include, but it throws exception:

System.InvalidOperationException: The expression '[n].Description' passed to the Include operator could not be bound.

Is there a way to achieve required behavior?

Upvotes: 0

Views: 67

Answers (2)

Camilo Terevinto
Camilo Terevinto

Reputation: 32068

If you don't map it at model creation time (the first time the context is instantiated), EF will never load it, unless you are willing to load it through reflection.

The only way to do this without reflection is to do this:

// When you DO want to load it
var x = context.X.Find(id);

// When you DON'T want to load it
var x = context.X
    .Where(y => y.Id == id)
    .Select(y => new X /* Or a ViewModel */ { Id = y.Id, ... }) // all properties but Description
    .FirstOrDefault();

There is one more way, probably the worst, which would be to move Description to a new Table and load it when needed.

Upvotes: 2

Faizal Shap
Faizal Shap

Reputation: 1820

NotMapped attribute will tell the entity framework that this field should not be added to database table.

If you dont want certain fields then you can project the fields using select Also don't forget to remove NotMapped attribute.
E. G

    db.entity.where(p => p. Id == id).select(p => new EntityModel{ name=p.name}). ToList();

Upvotes: 0

Related Questions