EF Code first NotMapped Attribute

柔情痞子 提交于 2020-06-16 08:01:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!