yusuf
yusuf

Reputation: 1263

How can I define DataAnnotations with ViewModel?

I create my model classes with "ADO.NET Entity Data Model" so if I change my database, my model classes will change..

My first class from "ADO.NET Entity Data Model";

public partial class TableA
    {
        public TableA()
        {
            this.TableBs = new HashSet<TableB>();
        }

        public int TableAID { get; set; }
        public string TableAName { get; set; }

        public virtual ICollection<TableB> TableBs { get; set; }
    }

My second class from "ADO.NET Entity Data Model";

    public partial class TableB
    {
        public TableB()
        {
            this.TableAs = new HashSet<TableA>();
        }

        public int TableBID { get; set; }
        public string TableBName { get; set; }
        public int TableCID { get; set; }

        public virtual TableC TableC { get; set; }
        public virtual ICollection<TableA> TableAs { get; set; }
    }

My third class from "ADO.NET Entity Data Model";

    public partial class TableC
    {
        public TableC()
        {
            this.TableBs = new HashSet<TableB>();
        }

        public int TableCID { get; set; }
        public string TableCName { get; set; }

        public virtual ICollection<TableB> TableBs { get; set; }
    }

And my ViewModel;

public class MyViewModel
{
    public TableA tableA { get; set; }
    public IEnumerable<TableB> tableBs { get; set; }
    public IEnumerable<TableC> tableCs { get; set; }
}

And I want to do this into my ViewModel;

    [Required]
    [Display(Name = "TableA Name")]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    public string TableAName { get; set; }

How can I do this??

Upvotes: 0

Views: 1716

Answers (1)

Display Name
Display Name

Reputation: 4732

ViewModel should not use your generated domain classes (TableA).

ViewModel example for TableA will be the following class:

public class TableAViewModel {

  [Required]
  public int Id { get; set }

  [Required]
  [Display(Name = "TableA Name")]
  [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
  public string Name { get; set; }

  IEnumerable<TableBViewModel> TableBViewModels { get; set; }
}

In the controller you will move retrieved properties from database by TableA class into TableAViewModel class. On postback from view you will move those properties back into TableA.

You can use AutoMapper to do that (for both objects and lists of objects)

Inside your view model TableAViewModel you can add data annotations the way like in my example (taken from your class). Its your classes to use, they aren't regenerated automatically by anything and its a good practice to use view models inside your views rather than domain (database) classes.

Hope this helps.

Upvotes: 3

Related Questions