.net 使用实体框架保存实体图

cx6n0qe3  于 2023-11-20  发布在  .NET
关注(0)|答案(1)|浏览(149)

我正在使用Entity Framework 6编写数据访问层。我想要的是,当我在DbContext上调用SaveChanges()方法时,它将保存实体以及通过导航属性关联的相关实体集。以下是我尝试执行的简单代码。

public class Customer
{
    public long ID { get; set; }
    public string Name { get; set; }

    public virtual IEnumerable<PhoneNumber> { get; set; }
}

public class PhoneNumber
{
    public long ID { get; set; }
    public string Number { get; set; }
}    

public class SampleContext : DbContext
{
    public virtual DbSet<Customer> Customers { get; set; }
    public virtual DbSet<PhoneNumber> PhoneNumbers { get; set; }
}

using(var context = new SampleContext())
{
     var customer = new Customer { ID = 1, Name = "John" };
     customer.PhoneNumbers = new PhoneNumbers[]
     {
          new PhoneNumber { ID = 1, Number = "1.111.1111111" },
          new PhoneNumber { ID = 2, Number = "1.111.1111112" }
     }
     context.Customers.Add(customer);
     context.SaveChanges();
}

字符串
上面的代码将客户保存在customers表中,但在PhoneNumbers表中不保存任何内容。

wgmfuz8q

wgmfuz8q1#

奇怪,但找到了一个解决方案。上述代码需要一点修改,使其工作。以下是修改:

// In Customer class, changed following line:
 public virtual IEnumerable<PhoneNumber> { get; set; }

 // To:
 public virtual ICollection<PhoneNumber> { get; set; }

 // Then in using block initialized entities as follows:
 using(var context = new SampleContext())
 {
      var customer = new Customer { ID = 1, Name = "John", PhoneNumbers = new List<PhoneNumber>() };
      customer.PhoneNumbers.Add(new PhoneNumber { ID = 1, Number = "1.111.1111111" });
      context.Customers.Add(customer);
      context.SaveChanges();
 }

字符串

相关问题