问题
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