问题
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.
回答1:
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
回答2:
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.
回答3:
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
来源:https://stackoverflow.com/questions/20660425/ef-code-first-notmapped-attribute