4

我正在评估 EF4 并且有一个非常基本的问题......我认为,我似乎无法找到答案......

举个例子:

public class Question
{
  public string question {get;set;}
  public string answer {get; set;}
}

public class Person
{
  public string Id {get; set;}
  public string Name {get; set;}
  public List<Question> Questions {get; set;}
}

然后我在数据库中有以下表

Person
(
 id,
 name
)

Question
(
 id,
 personId,
 question,
 answer,
)

我是否可以先使用 EF4 代码将 Person 类映射到两个表,或者我是否应该首先重构我的 POCO 以便问题类包含 id 和 personId - 这不是我想做的事情。

我可以在 OnModelCreating 中添加一些东西来映射我需要映射的类吗?

谢谢!

4

1 回答 1

0

好的,这就是我现在所做的 - 但它需要我必须重组我的问题类......

public class Question
{  
    public int Id {get;set;}   /* New */
    public int PersonId {get;set;}  /* New */
    public string question {get;set;}  
    public string answer {get; set;}

    public virtual Person PersonObj {get;set;}
}

public class Person
{  
    public string Id {get; set;}  
    public string Name {get; set;}  
    public List<Question> Questions {get; set;}
}

并在 OnModelCreating 事件中添加以下内容

 modelBuilder.Entity<Person>().
                    HasMany(d => d.Questions).
                    WithRequired(c => c.Person).
                    HasForeignKey(c => c.PersonId).
                    WillCascadeOnDelete();

不确定它是否完全正确......但现在似乎正在工作。

于 2010-12-09T12:48:57.917 回答