简体   繁体   English

ASP.NET MVC4表,其中一列是主键

[英]ASP.NET MVC4 Table with one column that is the primary key

I'm using: 我正在使用:

  • ASP.NET MVC4 ASP.NET MVC4
  • Visual Studio 2012 Visual Studio 2012
  • Linq2SQL LINQ2SQL
  • SQL Server 2008 R2 SQL Server 2008 R2

I've got a table Role : 我有一张桌子角色

角色表

(One column that's called RoleName , datatype varchar(50) and is the primary key) (一列称为RoleName ,数据类型为varchar(50)并且是主键)

When I create a strongly-typed view with as model class Roles (extra 's' is caused by pluralisation, no issue) and scaffold template Edit , the result is that I only get a hidden field and no edit/input field, as shown below: 当我创建一个强类型视图作为模型类Roles (额外's'是由多元化,没有问题引起)和scaffold模板Edit时 ,结果是我只得到一个隐藏字段而没有编辑/输入字段,如图所示下面:

<fieldset>
    <legend>Role</legend>

    @Html.HiddenFor(model => model.RoleName)

    <p>
        <input type="submit" value="Save" />
    </p>
</fieldset>

This is likely due to the only column being the primary key which MVC uses to identify the database record. 这可能是由于唯一的列是MVC用于标识数据库记录的主键。

I want to be able to edit every Role's RoleName. 我希望能够编辑每个Role的RoleName。 How can I make an edit page for a table with one column that is the primary key? 如何为包含一列主键的表创建编辑页面?

Just adjust the scaffolded HTML markup to fit what you need. 只需调整脚手架HTML标记即可满足您的需求。 You are correct that MVC made that hidden because it is a primary key. 你是正确的,MVC隐藏了它,因为它是一个主键。 Unhide it. 取消隐藏它。

<fieldset>
    <legend>Role</legend>

    @Html.TextBoxFor(model => model.RoleName)

    <p>
        <input type="submit" value="Save" />
    </p>
</fieldset>

However, and this may just be subjective, I think having an int based primary key will go a long ways in doing things like: 然而,这可能只是主观的,我认为拥有一个基于int的主键将在很长的路要走:

  1. Not having a DB exception thrown if you accidentally edit or add a role name that matches an existing role name. 如果您不小心编辑或添加与现有角色名称匹配的角色名称,则不会引发数据库异常。
  2. Save space in your DB when you go to attach users to roles. 当您将用户附加到角色时,可以节省数据库中的空间。 Instead of having a varchar(50) duplicated for each user/role, you will only have an int duplicated. 不是为每个用户/角色复制varchar(50),而是只复制一个int。 (UserId / RoleId) (UserId / RoleId)
  3. Quicker/better indexing on integers than varchars 比varchars更快/更好地对整数建立索引

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM