|
Dasturiy injiniring (EntityFramework 6)
|
bet | 41/53 | Sana | 30.11.2023 | Hajmi | 1,39 Mb. | | #108476 |
Bog'liq Dasturiy injiniringFluentContext.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);
modelBuilder.Entity().Property(p => p.Name).HasColumnName("PhoneName");
modelBuilder.Entity().Property(p => p.Name).HasMaxLength(50);
modelBuilder.Entity().Property(p => p.Name).HasColumnType("varchar");
modelBuilder.Entity().Property(p => p.Price).HasPrecision(15, 2);
// Fluent APIdan 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 < 25000)
.Union(db.Phones.Where(p => p.Name.Contains("Samsung")));
foreach (var item in phones)
Console.WriteLine("{0} - {1}", item.Name, item.Price);
}
Console.ReadKey();
}
}
}
Modelni bir qancha jadvallarga mos qo’yish
Fluent API yordamida modelning bir nechta xususiyatlarini bitta jadvalga, boshqa xusuisiyatlarini boshqa jadval ustunlariga mos qo’yish mumkin:
modelBuilder.Entity().Map(m =>
{
m.Properties(p => new { p.Ident, p.Name });
m.ToTable("Mobiles");
})
.Map(m =>
{
m.Properties(p => new { p.Ident, p.Price, p.Discount });
m.ToTable("MobilesInfo");
});
Yuqoridagi usul orqali Name xususiyati Mobiles jadvalida saqlanadi. Price va Discount xususiyatlari esa MobilesInfo jadvalida saqlanadi. Identifikator ustuni esa har ikkala jadval uchun umumiy hisoblanadi.
Model va Fluent API o’rtasidagi munosabat
|
| |