Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 374
urig Avatar asked May 14 '14 05:05

urig


Video Answer


1 Answers

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>();
like image 113
haim770 Avatar answered Sep 22 '22 12:09

haim770