OverflowStack OverflowStack - 1 month ago 7
C# Question

Correct Usage of Entity Framework Generated Classes (DB First Approach)

I'm developing my first MVC5 website and it happens this is also the first time I'm using ET.

I'm using Database First approach.

For example, lets say these are my fields in Users table.

| Username | Email | Password |


And Entity Frameworks generate me the following class:

class Users
{
public string Username { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}


Now lets say I want to create a View for Registration. This registration requires user to confirm his password. Do I expand the existing ET generated class like this?

class Users
{
public string Username { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
}


Or do I make an entirely different class myself that will contain all the necessary information separately from ET generated class?

Do I make Views using ET generated classes, or do I use my own classes?

I've seen ViewModels being mentioned here and there, but it is not very clear to me as to what purpose they serve.

As of right now, I'm manually adding extra fields to ET classes, and it works, but I've no idea if I'm doing it wrong or right.

Answer

You should not touch your entity framework generated code for such requirement. Instead you need to create a view model to contain fields which you want to get from user when registration. You can create a RegisterViewModel. Then to compare those properties, use Compare attribute, exactly like what is used in ASP.NET MVC default project template. Then in controller, check if model state is valid, create a User entity using posted values an save in db:

Model

public class RegisterViewModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

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

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", 
    ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

Action

// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new User() { UserName = model.UserName, /*... other fields */ };
        // Save user
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}
Comments