Article

Salı, 25 Ağu 2020 - 21:08

Entity Framework DataAnnotations

Owner: Barış Gelebek

"Code-First Domain class oluşturmak için sıkça kullanılan dataannotation attiribut'ler veritabanının nesnel kopyaları sayılabilirler. Bu bağlamda datanın oluşması için gerekli olan malzemenin kural kısmıdır denilebilir. Şimdi bu attirbut'leri inceleyelim;"



Key Attribute

İlgili entity ile ilgili belirtmek istediğimiz property’i key olarak tanıtmak için kullanılır.

using System.ComponentModel.DataAnnotations;
 
public class Student
{
    public Student()
    {
 
    }
 
    [Key]
    public int StudentKey { getset; }
 
    public string StudentName { getset; }
 
}

yukardaki örneğe göre PackageId alanı key olarak tanımlanmış oldu.

Birden fazla alan Key olarak işaretlenebilir, ancak kullanım olarak Column Attribute’i ile tanımlanır.

using System.ComponentModel.DataAnnotations;
 
 
 
public class Student
 
{
 
    public Student()
 
    {
 
    }
 
    [Key]
 
    [Column(Order = 1)]
 
    public int StudentKey1 { getset; }
 
 
 
    [Key]
 
    [Column(Order = 2)]
 
    public int StudentKey2 { getset; }
 
 
 
    public string StudentName { getset; }
 
 
 
}

Eğer sadece tek bir integer alan Key olarak işaretlenmişse bu alan aynı zamanda identity olarak da belirlenir. yani sayı otomatik olarak üretilir. Birden fazla alanın identity olarak işaretlendiği key yapılarında bu alanlardan herhangi biri identity olarak işaretlenmez.

TimeStamp Attribute

Domain Class içinde sadece tek bir alanda olabilir. TimeStamp attribute timestamp tipinde bir kolon oluşturur Code-First bu kolonu concurency check için otomatik olarak kullanır.

using System.ComponentModel.DataAnnotations;
 
 
 
public class Student
 
{
 
    public Student()
 
    {
 
 
 
    }
 
 
 
    public int StudentKey { getset; }
 
 
 
    public string StudentName { getset; }
 
 
 
    [TimeStamp]
 
    public byte[] RowVersion { getset; }
 
}

ConcurrencyCheck Attribute

Bu alan birden fazla kullanıcının aynı kaydın farklı versiyonlarını kaydetmek istedikleri zaman concurency kontrollerini hızlıca yapmak için kullanılır. timestamp attribute’undan farklı olarak birden fazla alan concurencycheck olarak işaretlenebilir.

using System.ComponentModel.DataAnnotations;
 
 
 
public class Student
 
{
 
    public Student()
 
    {
 
 
 
    }
 
 
 
    public int StudentId { getset; }
 
 
 
    [ConcurrencyCheck]
 
    public string StudentName { getset; }
 
}

sonuç olarak oluşacak olan sql sorgusu aşağıdaki şekilde olacaktır.

exec sp_executesql N'UPDATE [dbo].[Students]
 
SET [StudentName] = @0
 
WHERE(([StudentId] = @1) AND([StudentName] = @2))
 
',N'@0 nvarchar(max) ,@1 int,@2 nvarchar(max) ',@0=N'Steve ',@1=1,@2=N'Bill '
 
go

Required Attribute

Tanımlanan alanı not null olarak işaretleyerek bu alana mutlaka bir değer girilmesini garanti eder.

using System.ComponentModel.DataAnnotations;
 
    
 
public class Student
 
{
 
    public Student()
 
    {
 
 
 
    }
 
    public int StudentID { getset; }
 
 
 
    [Required]
 
    public string StudentName { getset; }
 
 
 
}

MaxLength Attribute

Maxlength attribute’u strting yada array tipli propertylere uygulanabilir. Bu attribute ile ilgili kolonunun alan uzunluğu sql’de set edilir.

using System.ComponentModel.DataAnnotations;
 
    
 
public class Student
 
{
 
    public Student()
 
    {
 
 
 
    }
 
    public int StudentID { getset; }
 
 
 
    [MaxLength(50)]
 
    public string StudentName { getset; }
 
 
 
}

Entity framework belirlenen uzunluğun aşılması durumunda EntityValidationError throw edilir.

MinLength Attribute

MinLength attribute’u bir validation attribute’dür. belirlenen uzunluktan daha az bir değer girilmesi durumunda yine EntityValidationError throw edilir.

using System.ComponentModel.DataAnnotations;
 
    
 
public class Student
 
{
 
    public Student()
 
    {
 
 
 
    }
 
    public int StudentID { getset; }
 
 
 
    [MaxLength(50), MinLength(2)]
 
    public string StudentName { getset; }
 
 
 
}

StringLength Attribute

Maxlength ile hemen hemen aynıdır. Sadece string propertylerde kullanılabilir.

using System.ComponentModel.DataAnnotations;
 
 
 
public class Student
 
{
 
    public Student()
 
    {
 
 
 
    }
 
    public int StudentID { getset; }
 
 
 
    [StringLength(50)]
 
    public string StudentName { getset; }
 
 
 
}

Table Attribute

Table attribute bir class’a tanımlanabilir. Default olarak CodeFirst table isimlerini classname’den üretir ancak bu attribute ile belirlenen isimle bu tablo ismi overwrite edilir.

using System.ComponentModel.DataAnnotations.Schema;
 
 
 
[Table("StudentMaster")]
 
public class Student
 
{
 
    public Student()
 
    {
 
 
 
    }
 
    public int StudentID { getset; }
 
 
 
    public string StudentName { getset; }
 
 
 
}

aynı zamanda tablo ismi schema ismi de aşağıdaki şekilde kullanılabilir.

using System.ComponentModel.DataAnnotations.Schema;
 
 
 
[Table("StudentMaster", Schema = "Admin")]
 
public class Student
 
{
 
    public Student()
 
    {
 
 
 
    }
 
    public int StudentID { getset; }
 
 
 
    public string StudentName { getset; }
 
 
 
}

bu durumda yukardaki örneğe göre tablo Admin scheması içersinde Admin.StudentMaster şeklinde olacaktır.

Column Attribute

Column attribute’ü propertylere uygulanabilir. Default olarak property isimleri ile tabloda field isimleri oluşur. Ancak kolon ismin farklı vermek istersek columns atribute kullanılır.

using System.ComponentModel.DataAnnotations.Schema;
 
public class Student
{
    public Student()
    {
 
    }
 
    public int StudentID { getset; }

    [Column("Name")]
 
    public string StudentName { getset; }
 
}

Aynı zamanda Order ve Typename alanları aşağıdaki şekilde set edilerek de kullanılabilir.

using System.ComponentModel.DataAnnotations.Schema;
 
public class Student
{
    public Student()
    {
 
    }
 
    public int StudentID { getset; }
 
    [Column("Name", Order = 1, TypeName = "varchar")]
    public string StudentName { getset; }
}

ForeignKey Attribute

ForeignKey attribute propertylere uygulanır. Default olarak code-first entity linklerini otomatik olarak uygular ve FK alanlarını otomatik olarak oluşturur.

public class Student
{
    public Student()
    {
 
    }
 
    public int StudentID { getset; }
 
    public string StudentName { getset; }
 
    //Foreign key for Standard
 
    public int StandardId { getset; }
 
    public Standard Standard { getset; }
}
 
public class Standard
{
    public Standard()
    {
 
    }
 
    public int StandardId { getset; }
 
    public string StandardName { getset; }
 
    public ICollection<Student> Students { getset; }
}

ForeignKey attribute bu tanımlamayı overwrite eder bu alan için farklı isimli FK alanlarını oluşturmaya olanak sağlar.

public class Student
{
    public Student()
    {
 
    }
 
    public int StudentID { getset; }
 
    public string StudentName { getset; }
 
    //Foreign key for Standard
 
    public int StandardRefId { getset; }
 
    [ForeignKey("StandardRefId")]
    public Standard Standard { getset; }
}
 
public class Standard
{
    public Standard()
    {
 
    }
 
    public int StandardId { getset; }
 
    public string StandardName { getset; }
 
    public ICollection<Student> Students { getset; }
}
 
ForeignKey attribute’ü key property noktasında da aşağıdaki şekilde tanımlanabilir.
public class Student
{
    public Student()
    {
 
    }
 
    public int StudentID { getset; }
 
    public string StudentName { getset; }
 
    //Foreign key for Standard
 
    [ForeignKey("Standard")]
    public int StandardRefId { getset; }
    public Standard Standard { getset; }
}
 
public class Standard
{
    public Standard()
    {
 
    }
 
    public int StandardId { getset; }
 
    public string StandardName { getset; }
 
    public ICollection<Student> Students { getset; }
}

NotMapped Attribute

NotMapped attribute propertylere uygulanır. Default olarak code first get ve set propertyleri olan tüm kolonları tabloda oluşturur NotMapped attribute’ü uygulanarak belli bir alanın tablo’da oluşturulması engellenir.

using System.ComponentModel.DataAnnotations;
 
public class Student
{
    public Student()
    {
 
    }
 
    public int StudentId { getset; }
 
    public string StudentName { getset; }
 
    [NotMapped]
    public int Age { getset; }
}

Bununla birlikte Code-First default olarak get yada set propery’si olmayan alanları tabloda bir field olarak açmaz.

using System.ComponentModel.DataAnnotations;
 
public class Student
{
    public Student()
    {
 
    }
 
    private int _age = 0;
 
    public int StudentId { getset; }
 
    public string StudentName { getset; }
 
    public string FirstName { get { return StudentName; } }
 
    public string Age { set { _age = value; } }
}

InverseProperty Attribute

Code-First Foreignkey alanlarının isimlerini {classname}_{PrimaryKey} formülünü kullanarak oluşturur.

public class Student
{
    public Student()
    {
 
    }
 
    public int StudentID { getset; }
 
    public string StudentName { getset; }
 
    public Standard CurrentStandard { getset; }
 
    public Standard PreviousStandard { getset; }
}
 
public class Standard
{
    public Standard()
    {
 
    }
 
    public int StandardId { getset; }
 
    public string StandardName { getset; }
 
    public ICollection<Student> CurrentStudents { getset; }
 
    public ICollection<Student> PreviousStudents { getset; }
}

InverseProperty attribute’ü bu tanımlamayı override eder. bu durumda sonuç aşağıdaki şekilde olacaktır.

public class Student
{
    public Student()
    {
 
    }
 
    public int StudentID { getset; }
 
    public string StudentName { getset; }
 
    public Standard CurrentStandard { getset; }
 
    public Standard PreviousStandard { getset; }
}
 
public class Standard
{
    public Standard()
    {
 
    }
 
    public int StandardId { getset; }
 
    public string StandardName { getset; }
 
    [InverseProperty("CurrentStandard")]
    public ICollection<Student> CurrentStudents { getset; }
 
    [InverseProperty("PreviousStandard")]
    public ICollection<Student> PreviousStudents { getset; }
}

Yine foreignkey attribute’ü ile aşağıdaki şekilde kullanılabilir. her iki durumda da sonuç aynı olacaktır.

public class Student
{
    public Student()
    {
 
    }
 
    public int StudentID { getset; }
 
    public string StudentName { getset; }
 
    public int CurrentStandardId { getset; }
 
    public int PreviousStandardId { getset; }
 
    [ForeignKey("CurrentStandardId")]
    public Standard CurrentStandard { getset; }
 
    [ForeignKey("PreviousStandardId")]
    public Standard PreviousStandard { getset; }
}
 
public class Standard
{
    public Standard()
    {
 
    }
 
    public int StandardId { getset; }
 
    public string StandardName { getset; }
 
    [InverseProperty("CurrentStandard")]
    public ICollection<Student> CurrentStudents { getset; }
 
    [InverseProperty("PreviousStandard")]
    public ICollection<Student> PreviousStudents { getset; }
}





Tags:
Entity Framework Data Annotations Entity Framework Data Annotations
info:
Category: Entity Framework
Created on: 25.08.2020 21:13:35
Last View Date: 25.08.2020 21:13:35
Stats:
0 comments
249 views
17 likes

Comments: