c# - Entity Framework 生成的类的正确使用(数据库优先方法)

标签 c# asp.net-mvc entity-framework asp.net-mvc-4

我正在开发我的第一个 MVC5 网站,这也是我第一次使用 ET。

我正在使用数据库优先方法。

例如,假设这些是我在“用户”表中的字段。

| Username | Email | Password | 

Entity Framework 为我生成以下类:

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

现在假设我想创建一个注册 View 。此注册要求用户确认其密码。我是否可以像这样扩展现有的 ET 生成的类?

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

或者我自己创建一个完全不同的类,它将包含与 ET 生成的类分开的所有必要信息?

我是使用 ET 生成的类来创建 View ,还是使用我自己的类?

我到处都看到 ViewModel 被提及,但我不太清楚它们的用途。

截至目前,我正在手动向 ET 类添加额外的字段,并且它有效,但我不知道我这样做是错误还是正确。

最佳答案

您不应该接触 Entity Framework 为此类要求生成的代码。相反,您需要创建一个 View 模型来包含您希望在注册时从用户那里获取的字段。您可以创建一个RegisterViewModel。然后要比较这些属性,请使用 Compare属性,与 ASP.NET MVC 默认项目模板中使用的完全相同。然后在 Controller 中,检查模型状态是否有效,使用发布的值创建一个 User 实体并保存在数据库中:

型号

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; }
}

行动

// 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);
}

关于c# - Entity Framework 生成的类的正确使用(数据库优先方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40070860/

相关文章:

c# - 与 Entity Framework 在同一张表上的关系

entity-framework - Entity Framework 4还是数据集?

c# - 为什么 Web Api 向结果集添加额外的 $id

c# - 绑定(bind)到 ASP.NET MVC 中的强类型对象集合

c# - 在 Visual Studio Windows Azure 模拟器下运行 ASP.NET MVC 应用程序时创建正确的绝对 URL

c# - WCF 服务超时,然后执行操作?

c# - 如何在 Windows Mobile 中调试 .net 应用程序

c# - 为标签抓取 HTML,然后在单独的 DIV 标签中获取值

c# - File.Copy 与手动 FileStream.Write 用于复制文件

c# - 如何从动态 Entity Framework 存储过程返回表格字符串数据?