Search code examples
c#entity-frameworkentity-framework-6foreign-key-relationship

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


Solution

  • 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();