A model containing a list of the model's own type (recursive modeling?)

Well, that might be trivial, but I hope someone can give me a direct answer. Say you have two models in an MVC project, and one model contains a list of the other model. Two models would look something like this:

public class Vehicle { [Key] public int VehicleId { get; set; } public virtual List<Wheel> Wheels { get; set; } } public class Wheel { [Key] public int WheelId { get; set; } [Required] public int VehicleId { get; set;} [Required] public virtual Vehicle { get; set; } } 

Now say that you have the same thing, but with only one model. At first I thought it would look something like this:

 public class MyClass { [Key] public int MyClassId { get; set; } public string MyData { get; set; } public virtual List<MyClass> MyClasses { get; set; } } 

This only throws me off because MyClasses is listed as a navigation property. This would mean that each MyClasses[i] must have a MyClass property and another MyclassId that references the parent MyClass . After thinking about this for a while, I began to feel dizzy. Am I doing it right?

+4
source share
2 answers

This is the right approach to create a proper SQL database:

 public class MyClass { [Key] public int MyClassId { get; set; } public string Data { get; set; } public virtual Classes Classes { get; set; } } public class Classes { [Key] public int ClassesId { get; set; } [Required] public int MyClassId { get; set; } public List<MyClass> Classes { get; set; } [Required] public virtual MyClass MyClass { get; set; } } 
0
source

Working with an instance of MyClass :

 public class Class { [Key] public int ClassId { get; set; } public string Data { get; set; } } public class Classes { public virtual List<Class> Classes { get; set; } } 

In your view `@ model.ViewModels.Classes. It doesn't get any easier and don't push yourself dizzy than you expect.

In short, do not make circular links, break the circle, calling one class differently, so your model in the view will know what to look for and what to work with. Of course you can work with circles. The problem is that its a nightmare to maintain. Do yourself a favor and make your life easier.

Update

 public class MyClasses { public List<Classes> OtherClasses; } 

Hope this helps.

+1
source

All Articles