Entity Framework: Why is a property of type array of objects not persisted to DB?

為{幸葍}努か 提交于 2021-02-07 06:59:10

问题


I have two entities where one has a one to many relationship to the other. Example:

public class Question
{
    public int Id { get; set; }
    public string Text { get; set; }
    public Answer[] Answers { get; set; }
}

public class Answer
{
    public int Id {get; set; }
    public string Text { get; set; }
}

Using EF6 Code First I've setup this simple DbContext:

public class MyContext : DbContext
{
    public MyContext()
    {
        Database.SetInitializer<MyContext>(new DropCreateDatabaseAlways<MyContext>());
    }

    public DbSet<Question> Questions { get; set; }

    public DbSet<Answer> Answers { get; set; }
}

What I end up with in the DB are two similarly structured tables (int PK column and varchar column) and no representation of the "one Question has many Answers" relationship that I intended with the Question.Answers property.

Why doesn't EF Code First map the relationship and how can I fix this?


回答1:


Entity Framework doesn't support mapping navigation properties of bare Array types. The property has to be of Type that implements the ICollection<T> interface in order to be mapped.

Try to change your code as follows:

public class Question
{
    public int Id { get; set; }
    public string Text { get; set; }
    public virtual ICollection<Answer> Answers { get; set; }
}

And when initializing Answers, set it to a HashSet or List:

this.Answers = new List<Answer>();


来源:https://stackoverflow.com/questions/23646461/entity-framework-why-is-a-property-of-type-array-of-objects-not-persisted-to-db

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