Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a view model with an object or properties [closed]

Tags:

c#

asp.net-mvc

I am creating my first MVC project, and was curious as to which is the correct way to expose my Code First Entity Classes to my view model. I have a entity class like so:

public class Product
{
    public int Id { get; set; }
    public int CategoryId { get; set; }
    [StringLength(50)]
    public string ProductName { get; set; }
    public Nullable<System.DateTime> DateAdded { get; set; }
    [StringLength(50)]
    public string AddedBy { get; set; }
}

Is it better to pass in the object, or pass in the a new class of the properties?

public class ProductViewModel
{
    Product myProduct { get; set; }
}

public class ProductViewModel
{
    public int Id { get; set; }
    public int CategoryId { get; set; }
    public string ProductName { get; set; }
    public DateTime DateAdded { get; set; }
    public string AddedBy { get; set; }
}
like image 607
ios85 Avatar asked Nov 27 '25 16:11

ios85


1 Answers

It's better to go with the second option. It's generally bad practice to use your database classes as models. What your first option essentially does is just that, except it wraps it inside another pointless class.

What I'd do though, is have them both implement an interface, that way if you ever want to change it, just change the interface, then both instances can be changed.

public class ProductViewModel : IProduct
{
    public int Id { get; set; }
    public int CategoryId { get; set; }
    [StringLength(50)]
    public string ProductName { get; set; }
    public DateTime DateAdded { get; set; }
    [StringLength(50)]
    public string AddedBy { get; set; }
}
like image 100
mattytommo Avatar answered Nov 30 '25 06:11

mattytommo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!