实体框架6添加外键

时间:2015-12-21 22:59:57

标签: c# entity-framework entity-framework-6 foreign-key-relationship

我有一个模特

public class Order
{
    [Key]
    public int ID { get; set;}

    public string Name { get; set; }
}

public class Consumer
{
    public virtual List<Order> Orders { get; set;}
}

我遇到的问题是当你创建一个Consumer对象并引用现有的Order时,是否可以通过订单ID并允许实体框架完成剩下的工作。

我能让它发挥作用的唯一方法如下:

//Look up order
var order = dbContext.Order.Where(x=>x.ID == orderID)
var consumer = new Consumer { new List{ order} };
dbContext.Consumer.Add(consumer);

如果没有查询订单,有没有办法做到这一点?只需插入订单密钥的示例?像这样:

var consumer = new Consumer {
    new List { 
       new Order { ID = orderID } 
    } 
};
dbContext.Consumer.Add(consumer);

注意:最大的区别是我只是传递“orderID”而不必实际传递整个Order对象。

更新

public class Order
{
    [Key]
    public int ID { get; set;}

    public string Name { get; set; }

    public virtual List<Order> InheritedOrders{ get; set;}
}
DbContext中的

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    modelBuilder.Entity<EntityClass>().HasMany(x=>x.InheritedOrders).WithMany().Map(cs =>
            {
                cs.MapLeftKey("ParentID");
                cs.MapRightKey("ChildID");
                cs.ToTable("OderInheritance");
            });
}

在这种情况下,如果您引用同一个ype的对象并使用自动生成的WithMany生成的表,它将如何工作?

谢谢, d

2 个答案:

答案 0 :(得分:2)

您需要在订单模型中有一个参考密钥。像这样:

public class Order
{
    [Key]
    public int ID { get; set;}

    public string Name { get; set; }

    public int ConsumerId { get; set; }

    public virtual Consumer Consumer { get; set; }
}

public class Consumer
{
    public Consumer()
    {
        this.Orders = new HashSet<Order>();
    }

    public virtual List<Order> Orders { get; set;}
}

然后您可以在没有订单的情况下添加消费者。

var consumer = new Consumer { };
dbContext.Consumer.Add(consumer);

稍后当您添加订单时,您可以像这样附加消费者......

var order = new Order {
    Id = 1,
    Name = "Order 1",
    ConsumerId = 1
};
dbContext.Order.Add(order);

然后像这样查询...

foreach (Order order in Consumer.Orders)
{
    // do something with each order.
}

<强>更新

根据您的上述问题,我假设您的意思是如何找到子订单?如果您使用Fabio提供的代码,您可以像这样获取记录......

foreach (var order in Consumer.Orders.ChildOrders)
{
    // Do something with the child orders
}

或嵌套

foreach (var order in Consumer.Orders)
{
    // parent order

    foreach (var childOrder in order.ChildOrders)
    {
        // child orders of parent.
    }
}

答案 1 :(得分:2)

你可以像这样建立自我关系(1:n):

public class Order
{
    [Key]
    public int ID { get; set;}

    public string Name { get; set; }

    public int? ParentOrderId{ get; set; }

    public virtual Order ParentOrder { get; set; }

    public virtual ICollection<Order> ChildOrders { get; set; }
}

映射:

modelBuilder.Entity<Order>()
    .HasOptional(i => i.ParentOrder)
    .WithMany(i => i.ChildOrders)
    .HasForeignKey(i => i.ParentOrderId)
    .WillCascadeOnDelete(false);

插入订单(如@ sgtrice1所说):

var order = new Order 
{
    Name = "Order 1",
    ParentOrderId = 1 // FK HERE, IT WILL MAKE THE RELATIONSHIP
};
dbContext.Order.Add(order);
dbContext.SaveChanges();