Entity framework code first - map class with List<> of another class to multiple tables?

青春壹個敷衍的年華 提交于 2019-12-10 17:37:42

问题


I'm evaluating EF4 and have a pretty basic question...I think, that I can't seem to find an answer for..

take the following example:

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

Then I have the following tables in the database

Person
(
 id,
 name
)

Question
(
 id,
 personId,
 question,
 answer,
)

Can I use the EF4 code first to map the Person class to the two tables, or do I ahve to restructure my POCO's first so the question class contains the id and personId - which is not something I would like to do.

Can I add something to the OnModelCreating to map the class as I need it to be mapped?

Thanks!


回答1:


Ok here's what I've done for now - but it requires me having to restructure my question class...

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

and added the following in the OnModelCreating event

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

Not sure it's fully right...but seems to be working for now.



来源:https://stackoverflow.com/questions/4389265/entity-framework-code-first-map-class-with-list-of-another-class-to-multiple

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