实体框架代码首先为同一主/外键保存多个记录

时间:2011-09-01 21:22:46

标签: entity-framework entity-framework-4.1 ef-code-first

Person有两个相似的表,不同的是每个人在PersonPreference表中只有一个记录,但在PersonRoles表中可以有很多。 PersonPreference和PersonRole都具有相同的主键和外键(Person_ID):

<Table("Person")> _
Public Class Person
    <Key()> _
    Public Property Person_ID As Integer
    Public Property Name As String

    Public Overridable Property PersonPreference As PersonPreference
    Public Overridable Property PersonRoles As ObservableCollection(Of PersonRole)
End Class

<Table("PersonPreference")> _
Public Class PersonPreference
    <Key()> _
    Public Property Person_ID As Integer
    Public Property Car As String
    Public Property Color As String
End Class

<Table("PersonRole")> _
Public Class PersonRole
    <Key()> _
    Public Property Person_ID As Integer
    Public Property Role As String
End Class

Public Class PersonMap
    Inherits EntityTypeConfiguration(Of Person)

    Public Sub New()
        Me.HasRequired(Function(t) t.PersonPreference).WithRequiredPrincipal()
        Me.HasRequired(Function(t) t.PersonRoles).WithRequiredPrincipal()
    End Sub

End Class

有没有一种方法可以保存人员角色,因为它是代码(没有添加Roles表)或者需要修改(PersonRoles表上的主键 - 我尝试在PersonRoles表中创建复合键,但是那样做了不行?)

1 个答案:

答案 0 :(得分:1)

没有必要拥有Role表,但您需要在PersonRole表中有一个复合键。我不熟悉VB.net,所以希望你能把它转换成VB.net。

public class Person
{
    public int Id { get; set; }

    public string Name { get; set; }

    public virtual ICollection<PersonRole> PersonRoles { get; set; }

    //other properties
}

public class PersonContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>().HasMany(p => p.PersonRoles).
          WithRequired().HasForeignKey(r => r.PersonId);

        modelBuilder.Entity<PersonRole>().HasKey(r => new {r.PersonId, r.Role});
    }

    public DbSet<Person> Persons { get; set; }
}

这是一个例子

var ctx = new PersonContext();

var person = new Person {Name = "Foo"};
person.PersonRoles = new List<PersonRole>() 
      { new PersonRole { Role = "a" }, new PersonRole { Role = "b" } };

ctx.Persons.Add(person);

ctx.SaveChanges();