Initiating objects with mutual dependency
I'm trying to model entities from a film database. I have films which have a list of directors and directors which have a list of films. Objects I made are like this:
public class eFilm
{
//Basic properties
public int ID { get; private set; }
public string Title { get; set; }
public DateTime? Date { get; set; }
public List<eDirector> Directors = new List<eDirector>();
public List<eActor> Actors = new List<eActor>();
public eMedia_Type Type;
/// <summary>
/// Initiate a new Films from Films_Data object
/// </summary>
/// <param name="Film">Films_Data object from which to initiate a new film</param>
public eFilm(Film Film)
{
this.ID = Film.ID;
this.Title = Film.Title;
this.Date = Film.Date;
this.Synopsis = Film.Synopsis;
//Add directors
Film.Films_Directors.Select(fd => fd.Director).ToList<Director>().ForEach(d => this.Directors.Add(new eDirector(d)));
//Add actors
Film.Films_Actors.Select(fa => fa.Actor).ToList<Actor>().ForEa开发者_C百科ch(a => this.Actors.Add(new eActor(a)));
//Add type
this.Type = new eMedia_Type(Film.Media_Type);
}
}
public class eDirector
{
public int ID { get; private set; }
public string Name{ get; set;}
public List<eFilm> Films = new List<eFilm>();
public eDirector(Director Director)
{
this.ID = Director.ID;
this._Name = Director.Name;
_Number_Of_Films = Director.Films_Directors.Select(d => d.Film).ToList<Film>().ForEach(f => this.Films.Add(new eFilm(f)));
}
}
I've omitted some stuff for brevity. This gives me a stack overflow because I add directors to films which then adds films to directors which adds directors to films etc. I can't figure out a way to model this, but there obviously must be some way to do this since the entity framework can...
Any advice on how to proceed would be much appreciated.
EDIT: Some info that might be needed. I am doing this to add a layer on top of the classes generated by Linq-to-SQL, to enable me to perform some checks on data before I pass it to the repository for persistence. I am using c# and ASP.NET MVC.
What you've done is an unlimited loop, films adding directors which adds films until it throws a StackOverflowException, the reason why entity framework "can" do this is because by default entity framework is doing what is called lazy loading, which means that when you access the list of directors it makes a call to the database and gets them, the way your entities are now however they will eager load since the virtual keyword is used to have entity framework do lazy loading.
My suggestion would be that if you want to imitate the behavior of entity framework is to do something like this:
public class Film {
...
public readonly IEnumerable<Director> Directors = _repository.GetDirectors(this.iD);
}
you would then add a similar property in the Director class, this way you get the data only when you need it and it won't do an infinite loop in order to eager load everything.
精彩评论