实体框架:为什么对象数组类型的属性没有持久化到 DB? [英] Entity Framework: Why is a property of type array of objects not persisted to DB?

查看:59
本文介绍了实体框架:为什么对象数组类型的属性没有持久化到 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; }
}

首先使用 EF6 代码我已经设置了这个简单的 DbContext:

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; }
}

我最终在数据库中得到的是两个结构相似的表(int PK 列和 varchar 列),并且没有表示我打算使用 Question.Answers 属性的一个问题有多个答案"关系.

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.

为什么 EF Code First 不映射关系,我该如何解决这个问题?

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

推荐答案

Entity Framework 不支持裸数组类型的映射导航属性.属性必须是实现 ICollection 接口的 Type 才能被映射.

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; }
}

并且在初始化Answers时,将其设置为HashSetList:

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

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

这篇关于实体框架:为什么对象数组类型的属性没有持久化到 DB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆