简体   繁体   中英

Entity Framework 6 Adding foreign key

I have a model

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

    public string Name { get; set; }
}

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

The problem I have is when you create a Consumer object and reference existing Order , is there a way to just pass the Order ID and allow entity framework to do the rest.

The only way I could get it to work is the following:

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

Is there a way to do this without the looking up the order? Example by just plugging in the order Key? Something like this:

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

Note: the big difference is that I just pass the "orderID" and don't have to actually pass the whole Order object.

Update :

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

    public string Name { get; set; }

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

in 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");
            });
}

In this case, how would it work since your reference an object of the same ype and your using a auto generated WithMany generated table?

Thanks, D

You would need to have a reference key in the order model. like so:

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;}
}

Then you can add the Consumer without an order.

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

Later when you add the Order you can attach the Consumer like so...

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

And query it back like so...

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

UPDATE

With your above question I'm assuming you mean how do you find the child orders? If you use the code Fabio provided you could fetch the records like so...

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

or nested

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

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

You can make a self-relationship (1:n) like this:

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; }
}

Mapping:

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

Insert Order (As @sgtrice1 said):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM