简体   繁体   中英

Cyclical reference error in MVC3 & Entity Framework 4

I admit using MVC3/EF4 has been a breeze and the context:models work better then I'd hoped (though I'm always leary of constructs/frameworks that make things happen behind some curtain, but hey I'm old school grey beard), and all went well until I hit this issue.
I've seen many postings related to this issue but don't know how to solve it in my case. Each table(entity) has an employeeID field and it can (and usually is) a different employee for most records in each table. Apparently only one table in the DbContext can have a 'virtual employee employee' (or whatever I choose to name it) defined or else I get the dreaded "cyclical reference error". Ideally I'd like all three tables to have it so I can easily access the employees name. I may have to override the OnModelCreating() but that's (fluent API) totally out of my league. Any EF gurus out there????

Models:

class meeting{
int meetingID; //key
string description  {get;set;}
int employeeID {get;set;}   // who scheduled
public virtual employee employee  {get;set;}
public virtual ICollection<agenda> agendas {get;set;}
}

class agenda{
int agendaID {get;set;}   // key
int employeeID  {get;set;}  // initiator
public virtual employee employee {get;set;}
public virtual ICollection<actionItem> actionItems {get;set;}
}

class actionItem{
int actioItemID {get;set;} //key
string description {get;set;}
int employeeID {get;set;} // action item lead
public virtual employee employee {get;set;}
}

class employee{
int employeeID  {get;set;}//key
string name {get;set;}
}

context:
public class meetings:DbContext{
public DbSet<meeting> meetings {get;set;}
public DbSet<agenda> Agendas
public DbSet<actionItem> actionItems{get;set;}
}

I assume you're getting this error on serialization of your models. Most people use a second set of models to abstract from the EF models, but if you want to stick with those, use the approach from this answer to get rid of your cyclical reference problem:

EF 4.1 - Code First - JSON Circular Reference Serialization Error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM