Basit CodeFirst + Attribute Örneği - 2

Basit CodeFirst + Attribute Örneği – 2

CodeFirst, C# projemizde kod ile veritabanı oluşturma işlemiydi. Yeni bir proje oluşturup projemize Entity Framework’ü komut ekranından yada solution explorer’da projenizi sağ tuş yaparak Manage NuGet Packages alanından yükleyebiliyorduk.

Müşteri, Sipariş ve Context classlarımızı yazıyoruz:

    [Table("Musteriler")]     public class Musteri     {         [Key]         public int ID { get; set; }         [Required, MaxLength(75)]         public string AdiSoyadi { get; set; }         [Required, MaxLength(150)]         public string Adres { get; set; }         [MaxLength(15)]         public string Telefon { get; set; }          public virtual List<Siparis> Siparisler { get; set; }      }

    [Table("Siparisler")]     public class Siparis     {         [Key]         public int ID { get; set; }          [ForeignKey("Musteri")]         public int MusteriID { get; set; }          [Required, MaxLength(5), Column(TypeName = "nchar")]         public string PizzaBoyu { get; set; }          [Required, MaxLength(6), Column(TypeName = "nchar")]         public string Icecek { get; set; }          public short PizzaAdedi { get; set; }         public short IcecekAdedi { get; set; }          [Column(TypeName ="money")]         public decimal Ucret { get; set; }          [Required, MaxLength(50)]         public string Malzeme { get; set; }          [Column(TypeName ="datetime2")]         public DateTime SiparisTarihi { get; set; }          public virtual Musteri Musteri { get; set; }      }
    public class Context : DbContext     {         public Context()         {             Database.Connection.ConnectionString = @"server=.; database=PizzaSiparisDB; uid=sa; pwd=123;";         }          public DbSet<Siparis> Siparisler { get; set; }         public DbSet<Musteri> Musteriler { get; set; }     }

Key: Primarykey

Required: Gereklilik

Table(“TabloAd”) : Oluşturulacak tablo adı

MaxLength(50) : Alanın kapasitesini

Column(TypeName =”money”): Sütunun tipini… Örneğin datetime2

[ForeignKey(“Musteri”)] : Foreignkey’i

[ ] attributelar köşeli parantez ile başlar ve biterler. İçerisindeki özellikler virgüllerle ayrılırlar.

Alıntı Attribute Tablosu:

System.ComponentModel.DataAnnotations.Schema attributes

AttributeDescription
TableThe database table and/or schema that a class is mapped to.
ColumnThe database column that a property is mapped to.
ForeignKeySpecifies the property is used as a foreign key in a relationship.
DatabaseGeneratedSpecifies how the database generates values for a property.
NotMappedApplied to properties or classes that are to be excluded from database mapping.
InversePropertySpecifies the inverse of a navigation property
ComplexTypeDenotes that the class is a complex type. *Not currently implemented in EF Core.

System.ComponentModel.Annotations attributes

AttributeDescription
KeyIdentifies one or more properties as a Key
TimestampSpecifies the data type of the database column as rowversion
ConcurrencyCheckSpecifies that the property is included in concurrency checks
RequiredSpecifies that the property’s value is required
MaxLengthSets the maximum allowed length of the property value (string or array)
StringLengthSets the maximum allowed length of the property value (string or array)

SQL Bilginiz varsa aşağıdaki attributeleri rahatlıkla anlayabilirsiniz:

[Column(TypeName = “varchar(200)”)]

[Column(TypeName = “decimal(5, 2)”)]

[Column(“blog_id”)] // Kolon adı

Notmapped ile bazı özellilkler dışarıda bırakılabilir:

[NotMapped] public DateTime LoadedFromDatabase { get; set; }

Classlarımızı tamamladıktan sonra Tools >> Package Manager Console ekranına gerelerek Migrationsların oluşması için enable-migrations komutu ile migrationa başlayabilir, oluşan Configuration classının içerisindeki AutomaticMigrationsEnabled değerini AutomaticMigrationsEnabled = true; yaparak, update-database komutuyla işlemlerinizi devam ettirebilirsiniz. Ayrıca bu işlemi kısaca enable-migrations -EnableAutomaticMigration komutu ile de yapabilirsiniz.


Yayımlandı

kategorisi

yazarı:

Yorumlar

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir