c# - Re-use inherited FK-Relationship? -
i creating application using c#/.net 4.5 , ef 6 , wondering if following somehow:
i have 2 base classes like:
public class baseitem { [key] public int id { get; set; } public list<baserevision> revisions { get; set; } } public class baserevision { [key] public int id { get; set; } public baseitem item { get; set; } }
now derive both of them following:
[table("contentitems")] public class contentitem : baseitem { public string contenttype { get; set; } } [table("contentrevisions")] public class contentrevision : baserevision { public string text { get; set; } }
this works fine , ef handles queries like:
var revisions = db.contentitems.where(i => i.revisions.any(r => (r contentrevision).text.contians("abc")));
this converted sql expect, "get rid if as
" (it causes more complication in other cases).
i tried using generics baseitem
, not supported ef tried following:
[table("contentitems")] public class contentitem : baseitem { public string contenttype { get; set; } public list<contentrevision> contentrevisions { get; set; } } [table("contentrevisions")] public class contentrevision : baserevision { public string text { get; set; } public contentitem contentitem { get; set; } }
so use above query like:
var revisions = db.contentitems.where(i => i.contentrevisions.any(r => r.text.contians("abc")));
but can't working using inherited foreign key "item_id" in "baseitems" table. ef allways wants create second fk-relation using new "contentitem_id" key in "contentitems" table, duplicate relation (and maybe cause other side-effects).
is somehow possible (or has better idea solve/improve problem/pattern)?
update: demo project can downloaded here. if add new migration create second fk-mapping not want...
edit :
you don't need add complicated relation here, that's oftype<> intended for.
when want access contentitems only, insteed of creating new list in inheriteded object use baseitem list , write :
(i baseitem) i.revison.oftype<contentitem>
you'll use common list storing of differents baseitems. compiler, it's developper error free because when using oftype<> func, you'll typed objects want.
initial answer : if initial problem of revisions not contentrevision , cause query fail on as
conversion, should write way :
var revisions = db.contentitems.where(i => i.revisions.oftype<contentrevision>.any(r => r.text.contains("abc")));
Comments
Post a Comment