回到目录
对于数据仓储大家应该都很熟悉了,它一般由几个仓储规范和实现它的具体类组成,而仓储的接口与架构本身无关,对于仓储的实现,你可以选择linq2Sql,EF,Nosql,及XML
等等,之前我介绍过linq2Sql,ef和nosql(redis)的仓储实现,今天主要说一下xml仓储的实现。
下面的相关核心代码
/// <summary> /// XML实体基类 /// </summary> public abstract class XMLEntity { private string id = Guid.NewGuid().ToString(); /// <summary> /// XML实体主键 /// </summary> public string ID { get { return id; } set { id = value; } } }
/// <summary> /// XML文件数据仓储 /// </summary> /// <typeparam name="TEntity"></typeparam> public class XMLRepository<TEntity> : IRepository<TEntity> where TEntity : XMLEntity, new() { XDocument _doc; string _filePath; public XMLRepository(string filePath) { _filePath = filePath; _doc = XDocument.Load(filePath); } public void Insert(TEntity item) { if (item == null) throw new ArgumentException("The database entity can not be null."); XElement db = new XElement(typeof(TEntity).Name); foreach (var member in item.GetType().GetProperties()) { db.Add(new XElement(member.Name, new XAttribute("value", member.GetValue(item, null)))); } _doc.Root.Add(db); _doc.Save(_filePath); } public void Delete(TEntity item) { if (item == null) throw new ArgumentException("The database entity can not be null."); XElement xe = (from db in _doc.Root.Elements(typeof(TEntity).Name) where db.Element("ID").Attribute("value").Value == item.ID select db) .Single() as XElement; xe.Remove(); _doc.Save(_filePath); } public void Update(TEntity item) { if (item == null) throw new ArgumentException("The database entity can not be null."); XElement xe = (from db in _doc.Root.Elements(typeof(TEntity).Name) where db.Element("ID").Attribute("value").Value == item.ID select db) .Single(); try { foreach (var member in item.GetType().GetProperties()) { xe.Add(new XElement(member.Name, new XAttribute("value", member.GetValue(item, null)))); } _doc.Save(_filePath); } catch { throw; } } public IQueryable<TEntity> GetModel() { IEnumerable<XElement> list = _doc.Root.Elements(typeof(TEntity).Name); IList<TEntity> returnList = new List<TEntity>(); foreach (var item in list) { TEntity entity = new TEntity(); foreach (var member in entity.GetType().GetProperties()) { member.SetValue(entity, item.Element(member.Name).Attribute("value").Value); } returnList.Add(entity); } return returnList.AsQueryable(); } public TEntity Find(params object[] id) { return GetModel().FirstOrDefault(i => i.ID == id[0]); } }
感觉面向对象也是一种病,但这种病我认为是正确的,当你对它的理解达到某种程度时,这种病就会犯了,并且你会相信,世间万物,皆为对象。
回到目录