公司的項目在用EF,最近抽時間研究了下,整理了一個比較公用的EF框架,供大家一起分享下。
EF這東東,用得好的話,確實方便了開發;用得不好的話,出了問題半天也找不出是什么原因。
現在就先介紹EF的簡單使用。主要分為以下5個項目
EF.Core:數據實體
EF.Data:C#實體跟數據表直接的映射
EF.Service:數據服務
EFFramework:公共類庫
EFSolution:測試項目
DbContext是EF比較重要的類,我們的數據庫訪問對象都必須繼承該類。下面就是我們要用到的數據上下文:

public class EFObjectContext : DbContext, IDbContext { public EFObjectContext(string nameOrConnectionString) : base(nameOrConnectionString) { //((IObjectContextAdapter) this).ObjectContext.ContextOptions.LazyLoadingEnabled = true; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { //dynamically load all configuration //System.Type configType = typeof(LanguageMap); //any of your configuration classes here //var typesToRegister = Assembly.GetAssembly(configType).GetTypes() string[] MapPath = { "EF.Data.dll" }; foreach (var path in MapPath) { var asm = Assembly.LoadFrom(path); var typesToRegister = asm.GetTypes() .Where(type => !String.IsNullOrEmpty(type.Namespace)) .Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>)); foreach (var type in typesToRegister) { dynamic configurationInstance = Activator.CreateInstance(type); modelBuilder.Configurations.Add(configurationInstance); } } //...or do it manually below. For example, //modelBuilder.Configurations.Add(new LanguageMap()); base.OnModelCreating(modelBuilder); } }
OnModelCreating方法是應用程序在初始化時將實體跟數據表的映射加載到數據上下文。
1、定義實體

public class BlogUser:BaseEntity { public string Name { get; set; } public int Age { get; set; } public string Address { get; set; } }
此處比較簡單,不再廢話。
2、定義映射

public partial class BlogUserMap : EntityTypeConfiguration<BlogUser> { public BlogUserMap() { this.ToTable("BlogUser"); this.HasKey(c => c.Id); } }
定義實體跟數據表的映射,實體之間一對一、一對多、多對多的關系也在此處定義。
3、定義數據服務

public interface IBlogUserService { IList<BlogUser> GetAllBlogUser(); }

public class BlogUserService : IBlogUserService { private readonly IRepository<BlogUser> _blogUserRepository; public BlogUserService(IRepository<BlogUser> blogUserRepository) { this._blogUserRepository = blogUserRepository; } public IList<BlogUser> GetAllBlogUser() { return _blogUserRepository.Table.ToList(); } }
測試程序如下:

static void Main(string[] args) { EngineContext.Initialize(false); Console.WriteLine("初始化完成"); IBlogUserService service = EngineContext.Current.Resolve<IBlogUserService>(); IList<BlogUser> users = service.GetAllBlogUser(); Console.ReadKey(); }
這就是EF的簡單使用。
源代碼下載地址:http://pan.baidu.com/s/1mgJ57Ck