2

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?
tereško
  • 58,060
  • 25
  • 98
  • 150
Gwasshoppa
  • 884
  • 12
  • 18
  • 1
    Sound like you just want a `[NotEqualTo("parentid")]` attribute that you would apply to `tileid` or `regionid` (or the other way around). [Foolproof](https://foolproof.codeplex.com/) have one if you dont want to write your own. –  Oct 25 '14 at 10:35
  • I have had a look at Foolproof and I think this would work. Thanks for the feedback :) – Gwasshoppa Oct 27 '14 at 19:34

0 Answers0