Entity Framework:代码优先

时间:2023-03-09 23:04:58
Entity Framework:代码优先

一、代码优先Code First

EF6支持Oracle ODT 12C Release 3 (net4.5)

DataModel(类)——》生成数据库DB

存在的数据库DB——》生成的数据模型(类)

二、创建或生成Model代码

(可利用Entity FrameWork Power Tools 生成Model代码)

先安装EFTools6.1ForVS2012 ,EF6.1版以上用EntityFramework.CodeTeplates.Csharp及自带的模板。

方式1、使用标注

/// <summary>
/// 景点类
/// </summary>
[Table("DESTINATIONS", Schema = "PAMS")]
public class Destination
{
[Column("DESTINATIONID", TypeName = "INT")]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int DestinationId { get; set; } [Column("NAME")]
public string Name { get; set; } [Column("COUNTRY")]
public string Country { get; set; } [Column("DESCRIPTION")]
public string Description { get; set; } [Column("PHOTO")]
public byte[] Photo { get; set; } public virtual List<Lodging> Lodgings { get; set; }
} /// <summary>
/// 住宿类
/// </summary>
[Table("LODGINGS", Schema = "PAMS")]
public class Lodging
{
[Column("LODGINGID", TypeName = "INT")]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int LodgingId { get; set; } [Column("NAME")]
public string Name { get; set; } [Column("OWNER")]
public string Owner { get; set; } [Column("TARDESTINATIONID", TypeName = "INT")]
public int? DestinationID { get; set; } [ForeignKey("DestinationID")]
public Destination Destination { get; set; }
} /// <summary>
/// 度假村类
/// </summary>
public class Resort : Lodging
{
[Column("ENTERTAINMENT")]
public string Entertainment { get; set; }
} /// <summary>
/// 宿舍类
/// </summary>
public class Hostel : Lodging
{
[Column("MAXROOM", TypeName = "INT")]
public int? MaxRoom { get; set; }
}

方式2:使用模板Builder

public class BreakAwayContext : DbContext
{
public DbSet<CodeFirst.Model.Destination> Destinations { get; set; }
public DbSet<CodeFirst.Model.Lodging> Lodgings { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new DestinationMap());
modelBuilder.Configurations.Add(new LodgingMap());
}
}
public class DestinationMap : EntityTypeConfiguration<CodeFirst.Model.Destination>
{
public DestinationMap()
{
this.HasKey(t => t.DestinationId);
Property(d => d.Name).IsRequired();
Property(d => d.Description).HasMaxLength();
} }
public class LodgingMap : EntityTypeConfiguration<CodeFirst.Model.Lodging>
{
public LodgingMap()
{
this.HasKey(t => t.LodgingId);
Property(d => d.Name).IsRequired();
Property(d => d.Owner).HasMaxLength();
this.Map<Lodging>(d => d.Requires("TYPE").HasValue("Standard"));
this.Map<Resort>(d => d.Requires("TYPE").HasValue("Resort"));
this.Map<Hostel>(d => d.Requires("TYPE").HasValue("Hostel"));
}
}

三、配置文件

<connectionStrings>
<add name=”BreakAwayContext ”, conectionstring=”” providerName=””>
</connectionStrings>

四、操作

1、添加

var destination = new CodeFirst.Model.Destination
{
Country = "Indonesia",
Description = "EcoTourism at its best in exquisite Bali",
Name = "Bali"
};
using (var context = new CodeFirst.DataAccess.BreakAwayContext())
{
if (context.Destinations.Count((t => t.Name == "Bali") < )
{
context.Destinations.Add(destination);
context.SaveChanges();
}
}

2、修改

using (var context = new CodeFirst.DataAccess.BreakAwayContext())
{
var canyon = (from d in context.Destinations where d.Name == "Bali" select d).Single();
canyon.Description = "227 mile long canyon.";
    context.Entry(gw)=EntityState.Modified;
context.SaveChanges();
}

3、删除

using (var context = new CodeFirst.DataAccess.BreakAwayContext())
{
//var toDelete = new CodeFirst.Model.Destination { d.Name="Bali"};
//context.Destinations.Attach(toDelete); //attach,状态由added改为unchanged
//context.Destinations.Remove(toDelete);
//context.SaveChanges(); context.Database.ExecuteSqlCommand("delete from pams.DESTINATIONS where Name='Bali'");//直接执行sql, }

五、查询

1、Load方法把数据加载到内存(LINQ写法,同foreach)

using (var context = new CodeFirst.DataAccess.BreakAwayContext())
{
var query = from d in context.Destinations where d.Country == "Australia" select d;
query.Load();// foreach 也可以
var count = context.Destinations.Local.Count;
}

2、ToList()一次性从数据库中查出数据

var Invoices=ctx.Invoie.ToList();
foreach(var result in Onvoices)
{.}

3、Find方法根据键值先从内存中查询,内存中没有才查询数据库。

var destination = context.Destinations.Find();

4、Single(),SingleOrDefault(),First()等可根据条件直接从数据库查。

var destination = context.Destinations.SingleOrDefault(d => d.Name == "Bali");

六、直接执行SQL语句

1、context.Database.ExecuteSqlCommand("delete from pams.DESTINATIONS where Name='Bali'");//直接执行sql,

2、 IEnumerable<Lodging> a=context.Database.SqlQuery(“Select * from ..”) 可直接转为定义的实体类型,任何类型,EF不跟踪

3、DbSqlQuery<Lodging> c=context.Lodging.SqlQuery(“select* from ..) EF跟踪返回的对象。

4、modelBuilder.Entity<singleEntity>().HasEntitySetName(“MyEntity”) 创建实体集不需要在DBContext中定义

IEnumerable<Lodging> a=(Context as IObjectContextAdapter).ObjectContext.CreateQuery<Lodging>(“select * from ..”) 这以后的linq查询条件可合并为一个SQL