EF:创建新的依赖对象并使用其属性分配父对象

时间:2017-10-04 19:26:53

标签: c# entity-framework

问题

正如标题所暗示的那样,我有一个父实体 - 客户 - 和一个从属实体 - 包裹。它们通过一对多关联连接。但是,客户有两个Parcel对象列表:目前正在处理它们和已经交付给他的那些 - CurrentParcels和ArchivedParcels。

考虑这种情况,当我首先创建一个Customer对象,然后创建Parcel时,我希望将其分配给该Customer。我设置了Parcel的属性" Customer"到我刚创造的那个。但是,我应该如何确定将附加,最新或存档的客户列表?现在,它被添加到存档的包裹中,这当然是不可接受的。

据我所知,有一个肮脏的解决方案 - 手动从存档中删除包裹,然后将其添加到当前,但听起来不太好。有没有办法解决这个问题?

代码段(简化)

客户和包裹模型

public class Customer
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }

    public virtual ICollection<Parcel> CurrentParcels { get; set; }
    public virtual ICollection<Parcel> ArchivedParcels { get; set; }
}

public class Parcel
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }

    public int CustomerId { get; set; }
    public Customer Customer { get; set; }
}

数据库上下文

public class ParcelsManagementDBContext : DbContext
{
    public ParcelsManagementDBContext() : base("parcels")
    {
        System.Data.Entity.Database.SetInitializer(
            new DropCreateDatabaseIfModelChanges<ParcelsManagementDBContext>());
    }

    protected override void OnModelCreating(DbModelBuilder mb)
    {
        // Foreign key constraints creation
        mb.Entity<Parcel>()
            .HasRequired(p => p.Customer)
            .WithMany(c => c.CurrentParcels)
            .HasForeignKey(p => p.CustomerId);
        mb.Entity<Parcel>()
            .HasRequired(p => p.Customer)
            .WithMany(c => c.ArchivedParcels)
            .HasForeignKey(p => p.CustomerId);
    }
}

客户代码

public void Code()
{
    var db = new ParcelsManagementDBContext();

    // Add new customers to db
    var cust = db.Customers.Add(new Customer()
    {
        Id = db.Customers.Count() + 1,
        Name = "Foo",
        Email = "1@2.mier"
    });

    // Add new parcel to db with created customer as owner
    var parcel = db.Parcels.Add(new Parcel()
    {
        Id = db.Parcels.Count() + 1,
        Name = "Toys",
        Source = "Pushkina str",
        Destination = "Kolotushkina str",
        Urgency = "high",
        Type = "usual",
        IsConfirmed = false,
        deliveryStarted = false,
        Customer = cust
    });
    db.SaveChanges();
    // So, here cust.ArchivedParcels will contain the parcel, but not the cust.CurrentParcels, if we fetch him from db again
}

0 个答案:

没有答案