c# - Create relationship between User and Addresses (1-Many) and Order and Address (1-1) -
i have user class each user can have multiple addresses.
i have order class each order can have 1 address.
i have following code , getting cascade delete errors, prior getting foreign key constraint issues , have fixed these already.
public class user : identityuser { public virtual icollection<purchase> purchases { get; set; } public virtual icollection<address> addresses { get; set; } } public class order { [key, foreignkey("user")] public string orderid { get; set; } public virtual user user { get; set; } [required, foreignkey("address")] public int addressid { get; set; } public virtual address address { get; set; } public virtual icollection<orderitem> items { get; set; } } public class address { public int id { get; set; } [required] public string userid { get; set; } public user user { get; set; } }
i unsure wrong now, assume cascade issue attempt implement 1-1 , 1-many relationship on address table.
the exact error this:
introducing foreign key constraint 'fk_dbo.purchases_dbo.aspnetusers_userid' on table 'orders' may cause cycles or multiple cascade paths. specify on delete no action or on update no action, or modify other foreign key constraints.
i getting error when executing statement in visual studio 2013 package manager console.
'update-package -force'
edit:
after following @erkaners suggestions starting rethink structure.
a 'user' can have many delivery addresses want. of our users ship multiple addresses , shouldn't have repeatedly type these adresses in.
an 'order' in-progress order , customer selects 1 of previous addresses, or enters new 1 when order created.
i have table 'orderhistory' completed orders.
now i'm thinking dont ever want address deleted because 'orderhistory' table won't able refer address anymore.
instead think should adding boolean column mark addresses active/inactive , drop cascade delete completely. better course of action?
this because there 2 paths can cause deletion of address. using fluent api can solve problem:
public class order { public string orderid { get; set; } [required, foreignkey("user")] public string userid { get; set; } public virtual user user { get; set; } [required, foreignkey("address")] public int addressid { get; set; } public virtual address address { get; set; } public virtual icollection<orderitem> items { get; set; } } public class address { public int addressid { get; set; } [foreignkey("user")] public string userid { get; set; } public user user { get; set; } [foreignkey("order")] public string orderid { get; set; } public order order { get; set; } } modelbuilder.entity<user>() .hasmany(u => u.addresses) .withrequired(a => a.user) .hasforeignkey(a => a.userid); .willcascadeondelete(false);
Comments
Post a Comment