My Entity won't cast to IEntityWithRelationships

南笙酒味 提交于 2020-01-07 01:52:07

问题


I am having trouble casting one of my entities to IEntityWithRelationsships. I am using a lot the method for getting context from an entity, and it's been working fine so far. I thought that entity need only to have one or more relationships defined in Model and that's it.

Here's little bit of my code:

public ActionResult Update(StavkaDokumentaVM stavka)
{
if (ModelState.IsValid)
{
    StavkaDokumenta st = AutoMapper.Mapper.Map<StavkaDokumenta>(stavka);

    db.StavkeDokumenta.Attach(st);
    db.ObjectStateManager.ChangeObjectState(st, EntityState.Modified);                
    db.SaveChanges();

    IEntityWithRelationships test = st as IEntityWithRelationships; // I get NULL here

    st = db.StavkeDokumenta.Include("RelationEnd1").Include("RelationEnd2")
        .Where(sd => sd.IdStavkaDokumenta == st.IdStavkaDokumenta).Single();

    test = st as IEntityWithRelationships; // Also get NULL
}
}

Entity in question has like 10 relations defined, so it shouldn't be problem.

What is going on here? I am really baffled.

UPDATE:

This is what I just did:

db.LoadProperty(st, "DokumentStavke");
IEntityWithRelationships test = st.DokumentStavke as IEntityWithRelationships; // I get NON NULL value;
test = st as IEntityWithRelationships; // I still get NULL.

Is this the way things are supposed to be?


回答1:


POCO entity does not implement IEntityWithRelationships. What you are doing is a hack dependent on dynamic proxy. Dynamic proxy generated by EF implements that interface but to have dynamic proxy correctly created you must pass all prerequisites.



来源:https://stackoverflow.com/questions/12358659/my-entity-wont-cast-to-ientitywithrelationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!