Sunday, 15 April 2012

Entity Framework creates underscore column when generating database -



Entity Framework creates underscore column when generating database -

i have simple object model follows...

public class product { public long productid { get; set; } public int categoryid { get; set; } public category category { get; set; } }

and

public class category { public long categoryid { get; set; } public list<product> products { get; set; } }

generating underlying database entityframework results in next schema...

products

productid categoryid category_categoryid

categories

categoryid

in products table, categoryid column set 0 while category_categoryid column contains id of category product belongs to.

how cause category id set in categoryid column , prevent category_categoryid column beingness generated?

apply foreignkey attribute category or categoryid property. , alter categoryid property type match categoryid of category class (both should long or int).

public class product { public long productid { get; set; } public long categoryid { get; set; } [foreignkey("categoryid")] public category category { get; set; } } public class category { public long categoryid { get; set; } public list<product> products { get; set; } }

or

public class product { public long productid { get; set; } [foreignkey("category")] public long categoryid { get; set; } public category category { get; set; } }

you can same via fluent mapping:

protected override void onmodelcreating(dbmodelbuilder modelbuilder) { modelbuilder.entity<product>() .hasrequired(p => p.category) .withmany(c => c.products) .hasforeignkey(p => p.categoryid) .willcascadeondelete(false); base.onmodelcreating(modelbuilder); }

entity-framework

No comments:

Post a Comment