sql server - Entity Framework 6.1 - Code-First One-to-Many on single entity: Can't map PK to FK? -
i'm trying one-to-many on single table/entity using code first. entity looks , works fine:
public class stockindex { [key] [databasegenerated(databasegeneratedoption.identity)] public int id { get; set; } [stringlength(45, minimumlength = 3)] public string name { get; set; } [stringlength(500)] public string description { get; set; } public list<component> components { get; set; } public stockindex parentstockindex { get; set; } public list<stockindex> stocksubindices { get; set; } public stockindex() { stocksubindices = new list<stockindex>(); } }
it creates table pk , fk, you'd expect:
create table [dbo].[stockindex] ( [id] int identity (1, 1) not null, [name] nvarchar (45) null, [description] nvarchar (500) null, [parentstockindex_id] int null, constraint [pk_dbo.stockindex] primary key clustered ([id] asc), constraint [fk_dbo.stockindex_dbo.stockindex_parentstockindex_id] foreign key ([parentstockindex_id]) references [dbo].[stockindex] ([id]) );
it works great. i've scaffolded crud , works. however, forces me fire additional query in controllers when doing edit, in order lookup , assign "parent" record new one. want access "parentstockindex_id" field in table can assign directly dropdown , skip lookup query. tried mapping it:
public class stockindex { [key] [databasegenerated(databasegeneratedoption.identity)] public int id { get; set; } [stringlength(45, minimumlength = 3)] public string name { get; set; } [stringlength(500)] public string description { get; set; } public list<component> components { get; set; } public int parentstockindex_id { get; set; } [foreignkey("parentstockindex_id")] public stockindex parentstockindex { get; set; } public list<stockindex> stocksubindices { get; set; } public stockindex() { stocksubindices = new list<stockindex>(); } }
but exception when running it, when data seeded in dbcontext:
unable determine principal end of 'myapp.models.stockindex_parentstockindex' relationship. multiple added entities may have same primary key.
i'm sure i'm doing wrong, without using fluent, if possible.
you should use public int? parentstockindex_id { get; set; }
, set parent not required (have seen question mark after int).
Comments
Post a Comment