DBContext
1 public class DBContext 2 { 3 private static IObjectContainer _db; 4 public static IObjectContainer DB 5 { 6 get 7 { 8 if (_db == null) 9 { 10 11 _db = Db4oFactory.OpenFile(Path); 12 } 13 return _db; 14 } 15 16 } 17 18 public static string _path; 19 public static string Path 20 { 21 get 22 { 23 if (string.IsNullOrEmpty(_path)) 24 { 25 _path = Directory.GetCurrentDirectory() + "\\db.yap"; 26 } 27 return _path; 28 } 29 } 30 31 }
在相同程序集的Model目录:
Model目录实例
1 public class Person 2 { 3 public string Name 4 { get; set; } 5 public int Age 6 { set; get; } 7 public override string ToString() 8 { 9 return Name; 10 } 11 }
业务逻辑层:
PersonBiz[业务逻辑层]实例
1 public class PersonBiz 2 { 3 public static List<string> GetList() 4 { 5 var query = from Person it in DBContext.DB.Query<Person>() select it.Name; 6 return query.ToList(); 7 } 8 public static Person Get(string name) 9 { 10 var p = GetByName(name); 11 if (p == null) 12 Insert(name,out p); 13 return p; 14 15 } 16 public static bool Insert(string name, out Person p) 17 { 18 p = GetByName(name); 19 if (p!=null) 20 return false; 21 else 22 { 23 p = new Person(); 24 p.Name =name; 25 DBContext.DB.Store(p); 26 DBContext.DB.Commit(); 27 return true; 28 } 29 30 } 31 public static bool Delete(string name) 32 { 33 var p = GetByName(name); 34 if (p == null) 35 return false; 36 else 37 { 38 39 40 DBContext.DB.Delete(p); 41 DBContext.DB.Commit(); 42 return true; 43 } 44 } 45 private static Person GetByName(string name) 46 { 47 return DBContext.DB.Query<Person>().Where(o => o.Name ==name).FirstOrDefault(); 48 } 49 50 }
Db4objects特点:CodeFirst,只要写好Model类运行后,程序会自动生成数据库结构.