I have an MVC project that has several recursive relationships in different models. See sample model structure below.
For example:
tileid and parentid
(a tile can be related to many tiles)regionid and parentid
(a region can be related to many regions)
I would like to create an MVC ValidationAttribute
called PreventRecursiveParent
that was dynamic enough to use throughout the system regardless of the Model, which prevented the user from assigning the parentid on a Model, to itself. i.e. prevent an infinite loop between the parent and the child.
e.g. A shortened sample Model would be as follows:
public partial class Tile
{
public Tile()
{
this.ChildTiles = new List<Tile>();
this.TileRoles = new List<TileRole>();
this.TileCompanies = new List<TileCompany>();
}
[Key]
public int tileid { get; set; }
[Required]
[Display(Name = "Tile Header")]
public string tileheading { get; set; }
//This is a recursive relationship where a tile can have a parent, but not itself.
[PreventRecursiveParent] //--> Attribute I would like to create <--
[Display(Name = "Parent Tile")]
public Nullable<int> parentid { get; set; }
public virtual Tile ParentTile { get; set; }
}
This issue is not so much when the user creates the Tile
as they are not able to assign the parentid
at that point, but when the user edits the Tile
.
When the user edits a Tile
they can select a ParentTile
from a list of tiles, and assign it to the currently selected Tile
.
I would like to ensure that the ParentTile
and therefore parentid
cannot be the same as the Tile
itself, but also use the same code throughout all the other recursive relationship Models.
Therefore my question is as follows:
- Can I use a generic attribute to attach to any
parentid
in a Model to prevent a user from assigning itself to itself, and if so how?