LuckyStrike
LuckyStrike

Reputation: 1493

EF Code first NotMapped Attribute

Why is in the following example the [NotMapped] attribute required:

public virtual ICollection<Blog> Blogs { get; set; }

[NotMapped]
    public List<Blog> NewBlogs{
        get{
            return Blogs.Where(x=>x.Date > DateTime.Now).ToList();
        }
    }

Without the [NotMapped] attribute I get an exception:

Invalid column name Blog_ID

The column name in the database is BlogID.

EDIT

I would expect, that properties without setter are never directly mapped to the database and automatically ignored by code first.

Upvotes: 4

Views: 16618

Answers (3)

Federico M. Rinaldi
Federico M. Rinaldi

Reputation: 353

Even if the property doesn't have a setter you could have that persisted in the database. i.e.: you have a model Product that sets a property like the Price in the constructor that you don't want to change (doesn't have a setter) but you want that value persisted in the DB

Upvotes: 0

kirie
kirie

Reputation: 342

with [NotMapped] attribute basically you mark that properties as not an Entity/Properties

so EF will not try to map/fetch that properties from database

that example actually say, NewBlogs is not Entity like Blogs. so stop try to get NewBlogs from database

Upvotes: 6

Robert Levy
Robert Levy

Reputation: 29083

It is marked as NotMapped because it returns data that is fetched from the DB on-demand instead of representing a separate set of entities to be stored.

Upvotes: 1

Related Questions