IdentityAttribute Class
.NET Standard 2.x
Specifies that the database generates a value for the property when a row is inserted.
Namespace: SnapObjects.Data
Assembly: SnapObjects.Data.dll
Inheritance Constructor
System.Attribute
Syntax
public class IdentityAttribute : Attribute
Examples
The following code example demonstrates how to use the Identity
attribute. In the Person class, the PersonID property is applied with the Identity
attribute. When a Person object is created, the PersonID property needs not to be assigned with a value, instead the database will automatically assign a value to it.
Model: Person
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using SnapObjects.Data;
namespace Appeon.ApiDoc.Models.School
{
/// <summary>
/// This model class maps to the dbo.Person table.
/// When Discriminator is 'Instructor', it represents an instructor record;
/// when Discriminator is 'Student', it represents a student record.
///
/// It uses the primary key to generate the Where clause for the Update operation.
///
/// PersonID is the pimary key and the identity.
/// </summary>
[Table("Person", Schema = "dbo")]
[UpdateWhereStrategy(UpdateWhereStrategy.KeyColumns)]
public class Person
{
[Key]
[Identity]
public int PersonID { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public DateTime? HireDate { get; set; }
public DateTime? EnrollmentDate { get; set; }
public string Discriminator { get; set; }
}
}
Example Method:
using Appeon.ApiDoc.Models.School;
namespace Appeon.ApiDoc.IdentityAttributeExamples
{
public class IdentityAttributeExample
{
private SchoolContext _context;
public IdentityAttributeExample(SchoolContext dataContext)
{
// Sets the data context.
_context = dataContext;
}
public void Example()
{
var mapper = _context.SqlModelMapper;
// Adds a Person record.
var person = new Person()
{
LastName = "Walker",
FirstName = "Kim",
Discriminator = "Student"
};
mapper.TrackCreate(person).SaveChanges();
/* The following INSERT SQL is generated:
exec sp_executesql N'INSERT
INTO [dbo].[Person] ([LastName], [FirstName], [Discriminator])
VALUES (@p0, @p1, @p2);
SELECT [PersonID]
FROM [dbo].[Person]
WHERE @@ROWCOUNT = 1 AND [PersonID] = scope_identity();
',N'@p0 nvarchar(4000),@p1 nvarchar(4000),@p2 nvarchar(4000)',
@p0=N'Walker',@p1=N'Kim',@p2=N'Student'
*/
}
}
}