The primary key int type, string type, and GUID type of the ASP. NET MVC Model class.

Source: Internet
Author: User

When defining a model class using ASP., we typically define a property of int id{get;set;} or int classnameid {get;set;}, in which case

1, int type primary key

The default convention for EF is that the first property, if it is the class name +id or the ID (in which case the ID letter case is not related), and is of type int, sets the first property as the primary key and sets the self-increment. You do not need to specify the [key] keyword (below the System.ComponentModel.DataAnnotations.Schema namespace)

Like what:

public class Person
{
public int ID {get; set;}

public string Name {get; set;}

public int price {get; set;}

Public DateTime Birthday {get; set;}
}

or for

public class Person
{
public int PersonId {get; set;}

public string Name {get; set;}

Public decimal price {get; set;}

Public DateTime Birthday {get; set;}
}

At this point, if the controller and view are automatically created with scaffolding, the attributes are not displayed in the Create,index view because the ID or CLASSID is already considered a primary key.

If you added [databasegenerated(databasegeneratedoption)in the field. None)], let you enter the primary key value yourself instead of the database to automatically create it.

The ID field is automatically displayed in the new and edited view for user input.

2. Guid PRIMARY key

Model:

public class Person
{
[Databasegenerated (Databasegeneratedoption.identity)]//This data annotations and can indicate that the GUID value can be automatically generated in the database, just tell the scaffolding to generate code to create the GUID value in the action method. such as person. PersonID = Guid.NewGuid ();
Public Guid PersonID {get; set;}

public string Name {get; set;}

public int price {get; set;}

Public DateTime Birthdaey {get; set;}


}

Automatically create controllers and views using scaffolding:

Public ActionResult Create ()
{
return View ();
}

Post:people/create
[HttpPost]
[Validateantiforgerytoken]
Public ActionResult Create ([Bind (Include = "Personid,name,price,birthdaey")] person person)
{
if (modelstate.isvalid)
{
Person .      PersonID = Guid.NewGuid (); //Scaffolding adds automatically created code that specifies the PersonID GUID property value.
Db. People.add (person);
Db. SaveChanges ();
Return redirecttoaction ("Index");
}

return View (person);
}

View: The PersonID form value is not already in the view that the scaffolding was generated because the database was automatically created in the model.

using (Html.BeginForm ())
{
@Html. AntiForgeryToken ()

<div class= "Form-horizontal" >
@Html. ValidationSummary (True, "", new {@class = "Text-danger"})


<div class= "Form-group";
@Html. labelfor (model = model. Name, htmlattributes:new {@class = "Control-label col-md-2"})

@Html. editorfor (model = Model. Name, new {htmlattributes = new {@class = "Form-control"}})
@Html. Validationmessagefor (model = model). Name, "", new {@class = "Text-danger"})
</div>
Span style= "Background-color: #ffff00;" > </div>

<div class= "Form-group" >
@Html. labelfor (model = model. Price, htmlattributes:new {@class = "Control-label col-md-2"})
<div class= "Col-md-10" >
@Html. editorfor (model = model. Price, new {htmlattributes = new {@class = "Form-control"}})
@Html. validationmessagefor (model = model. Price, "", new {@class = "Text-danger"})
</div>
</div>

3. String type primary key, if the property name of a model is ID or classnameid it is always considered a primary key, the mapping to the database is always the primary key value, and no key data annotations are required. Whether it is of type int or string, or GUID. If the int type is considered self-growing, the automatically generated edit view does not display this field. If the string type is not self-growing and requires user input or designation, the automatically generated edit view displays this field, prompting the user for input.

The first way: Create a constructor for the model to specify PersonID as the GUID string, and in the Create VIEW, delete the Perosnid form field values that the scaffolding automatically generates. In the Creater post method, the model binding automatically generates a Person object with its personid=guid value. This is a best practice for using a primary key type of string.

Model:

public class Person
{
public string PersonID {get; set;}//Because the property name is Classnameid, it is considered a primary key. But it does not grow from itself. Users are required to generate them themselves.

public string Name {get; set;}

Public decimal price {get; set;}

Public DateTime Birthday {get; set;}

Public person ()
{
PersonID = Guid.NewGuid (). ToString ();
}

Controller:

Get:people/create
Public ActionResult Create ()
{
return View ();
}

Post:people/create
To prevent an "excessive publishing" attack, enable the specific property you want to bind to,
For more information, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[Validateantiforgerytoken]
Public ActionResult Create ([bind (Include = "Personid,name,price,birthday")] the person person)//whether the binding PersonID is not affected.
{
if (modelstate.isvalid)//model binding will automatically create a person object, calling the person's constructor to generate a GUID primary key value.
{
Db. People.add (person);
Db. SaveChanges ();
Return redirecttoaction ("Index");
}

return View (person);
}

View: Delete automatically generated Perserid form fields.

@using (Html.BeginForm ())  
{
@Html. AntiForgeryToken ()

<div class= "Form-horizontal" >
@Html. ValidationSummary (True, "", new {@class = "Text-danger"}) & nbsp Delete the PersonID form field, if not deleted, then the value of PersonID will require manual input, no input will be bound to the PersonID in the Post method is a null value, the saved database will be an error.

<div class= "Form-group",
@Html. labelfor (model = model. Name, htmlattributes:new {@class = "Control-label col-md-2"})
<div class= "col-md-10";
@Html. Editorfor ( Model = model. Name, new {htmlattributes = new {@class = "Form-control"}})
@Html. validationmessagefor (model = model. Name, "", new {@class = "Text-danger"})
</div>
</div>

<div class= "Form-group" >
@Html. labelfor (model = model. Price, htmlattributes:new {@class = "Control-label col-md-2"})
<div class= "Col-md-10" >
@Html. editorfor (model = model. Price, new {htmlattributes = new {@class = "Form-control"}})
@Html. validationmessagefor (model = model. Price, "", new {@class = "Text-danger"})
</div>
</div>

The default string type primary key value used in the ASP. NET Identity is also the same implementation method. However, when we visit ApplicationUser, most of the bindings used are ViewModel, not the direct ApplicationUser or base class Identityuser classes.

View to ApplicationUser class (and user-related classes) inherited IdentityUser.cs (located in Microsoft.Asp.Net.Identity.EntityFramework.dll) after the source code is as follows:

 1Namespace Microsoft.AspNet.Identity.EntityFramework2 {3Using Microsoft.AspNet.Identity;4Using System;5 6 public class Identityuser:identityuser<string, Identityuserlogin, Identityuserrole, IdentityUserClaim , Iuser, iuser<string> 7 {8 public identityuser () 9 {10 this. Id = Guid.NewGuid (). ToString (); 11} 12 13 public identityuser ( String userName): this () 14 {15 this. UserName = UserName; 16} 17} 18}              

Observing IdentityUser.cs It had inherited identityuser<string, Identityuserlogin, Identityuserrole, Identityuserclaim>, IUser, Iuser<string> This generic, so we also need to have the corresponding int type of Identityuserlogin, Identityuserrole, Identityuserclaim generic class.

The second way: Specify a PersonID value directly in the controller crate post method.

Model classes remain unchanged, no constructors are used

public class Person
{
public string PersonID {get; set;}

public string Name {get; set;}

Public decimal price {get; set;}

Public DateTime Birthday {get; set;}

}

Controller:

The Get method of Create is kept consistent with the scaffold without modification.

The Post method removes the binding to the PersonID, which does not matter. )

Public ActionResult Create ()
{
return View ();
}

Post:people/create
To prevent an "excessive publishing" attack, enable the specific property you want to bind to,
For more information, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[Validateantiforgerytoken]
Public ActionResult Create ([Bind (Include = "name,price,birthday")] person person)
{
if (modelstate.isvalid)
{
Person . PersonID = Guid.NewGuid ().     ToString (); Create a GUID value in the Post method, convert it to a string, and assign a value to the PersonID property.
Db. People.add (person);
Db. SaveChanges ();
Return redirecttoaction ("Index");
}

return View (person);
}

In the view, delete the form fields that display the input Persornid.

The Third way: Create an empty object in the Create Get method, automatically call the constructor to generate the primary key value, return to the view, and then submit the form, passing the ID value through the model binding to the Create POST method. This method exposes the value of the user GUID to the first two methods.

Controller:

Model

public class Person
{
public string PersonID {get; set;} Because the property name is Classnameid, it is considered a primary key. But it does not grow from itself. Users are required to generate them themselves.

public string Name {get; set;}

Public decimal price {get; set;}

Public DateTime Birthday {get; set;}

Public person ()
{
PersonID = Guid.NewGuid (). ToString ();

}

Public ActionResult Create ()
{
person person = new person (); You can add this item to the scaffolding code and call the custom constructor to return a GUID value to the object in the Create view.
return View (person);
}

Post:desks/create

[HttpPost]
[Validateantiforgerytoken]
Public ActionResult Create ([bind (Include = personid,name,price,birthday]) ' person person ')//Bind table only son PersonID values come over.
{
if (modelstate.isvalid)
{
Db. People.add (person);
Db. SaveChanges ();
Return redirecttoaction ("Index");
}

return View (person);
}


}

CREATE VIEW Code:

@Html. ValidationSummary (True, "", new {@class = "Text-danger"})


<div class= "Form-group" >
@Html. labelfor (model = model. PersonID, htmlattributes:new {@class = "Control-label col-md-2"})
<div class= "Col-md-10" >
@Html. editorfor (model = model. PersonID, new {htmlattributes = new {@class = "Form-control"}})
@Html. validationmessagefor (model = model. PersonID, "", new {@class = "Text-danger"})
</div>
</div>

To keep the primary key field from appearing in the Create view, you can use @html. The hiddenfor (model =>model.personid) helper method replaces the above view code.

Summary: When using ASP. Codefirst, the primary key of the model Poco class can be defined as the int type, the GUID type (avoids the primary key value repeating in each table, the string type (converted by the GUID value). The crud operation method and corresponding view of the controller can be automatically generated using the scaffolding.

If a model's property name is ID or classnameid it is always considered a primary key, the mapping to the database is always the primary key value, and no key data annotations are required.

The primary key int type, string type, and GUID type of the ASP. NET MVC Model class.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.