问题
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