|
Dasturiy injiniring (EntityFramework 6)
|
bet | 39/53 | Sana | 30.11.2023 | Hajmi | 1,39 Mb. | | #108476 |
Bog'liq Dasturiy injiniringmodelBuilder.Ignore();
Birlamchi kalitni qayta aniqlash
Entity Framework boshlang‘ich holda birlamchi kalitni Id yoki model nomiga mos [Klass_nomi]Id kabi shakllantiradi. Misol: PhoneId.
Fluent API orqali birlamchi kalitni qayta aniqlash uchun HasKey() metodidan foydalaniladi.
modelBuilder.Entity().HasKey(p => p.Ident);
Ushbu holda birlamchi kalit sifatida Phone klassining Ident xususiyati tushuniladi. Agar birlamchi kalitlar sifatida ikkita maydon mos bo’lsa, u holda quyidagi koddan foydalaniladi:
modelBuilder.Entity().HasKey(p => new { p.Ident, p.Name });
Yuqoridagi modellarga mos dastur kodi quyidagicha:
App.config:
For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
Phone.cs:
class Phone
{
public int Ident { get; set; }
public string Name { get; set; }
public int Discount { get; set; }
public int Price { get; set; }
}
FluentContext.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
namespace Fluent
{
class FluentContext : DbContext
{
public FluentContext()
: base("DBConnect")
{ }
public DbSet Phones { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity().ToTable("Mobiles");
modelBuilder.Entity().HasKey(p => p.Ident);
// Fluent API dan foydalanish
base.OnModelCreating(modelBuilder);
}
}
}
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
namespace Fluent
{
class Program
{
static void Main(string[] args)
{
using (FluentContext db = new FluentContext())
{
// Samsung markali va narxi 650000 so’mdan kam telefonlar ro’yxati
var phones = db.Phones.Where(p => p.Price < 650000)
.Union(db.Phones.Where(p => p.Name.Contains("Samsung")));
foreach (var item in phones)
Console.WriteLine(item.Name);
// so’rovni amalga oshirish
var tels = db.Database.SqlQuery("SELECT * FROM Mobiles");
foreach (var phone in tels)
Console.WriteLine(phone.Name);
}
Console.ReadKey();
}
}
}
Xususiyatlarni moslashtirish
Klass xususiyatini muayyan ustun bilan mos qo’yish uchun HasColumnName() metodidan foydalaniladi::
modelBuilder.Entity().Property(p => p.Name).HasColumnName("PhoneName");
Ushbu holda klassning Name xususiyati bilan jadvalning PhoneName ustuni mos qo’yilgan. Agar biror xususiyat bilan jadvalning biror ustuni ususman mos qo’yilmasligi lozim bo’lsa, Ignore() metodidan foydalaniladi:
modelBuilder.Entity().Ignore(p => p.Discount);
Endi Phone klassidagi Discount xususiyati DBdagi jadalning biror ustuni bilan mos qo’yilmaydi.
|
| |