/// <summary>
/// XML文件数据仓储
/// XML结构为Attribute
/// </summary>
/// <typeparam name="TEntity"></typeparam>
public class XML2Repository<TEntity> :
IRepository<TEntity>
where TEntity : XMLEntity, new()
{
XDocument _doc;
string _filePath;
static object lockObj = new object();
public XML2Repository(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()
.Where(i => i.PropertyType.IsValueType
|| i.PropertyType == typeof(String)))
{
db.Add(new XAttribute(member.Name, member.GetValue(item, null) ?? string.Empty));
}
_doc.Root.Add(db);
lock (lockObj)
{
_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.Attribute("RootID").Value == item.RootID
select db).Single() as XElement;
xe.Remove();
lock (lockObj)
{
_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.Attribute("RootID").Value == item.RootID
select db).Single();
try
{
foreach (var member in item.GetType()
.GetProperties()
.Where(i => i.PropertyType.IsValueType
|| i.PropertyType == typeof(String)))
{
xe.SetAttributeValue(member.Name, member.GetValue(item, null) ?? string.Empty);
}
lock (lockObj)
{
_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()
.Where(i => i.PropertyType.IsValueType
|| i.PropertyType == typeof(String)))//只找简单类型的属性
{
if (item.Attribute(member.Name) != null)
member.SetValue(entity, Convert.ChangeType(item.Attribute(member.Name).Value, member.PropertyType), null);//动态转换为指定类型
}
returnList.Add(entity);
}
return returnList.AsQueryable();
}
public TEntity Find(params object[] id)
{
return GetModel().FirstOrDefault(i => i.RootID == Convert.ToString(id[0]));
}
public void SetDbContext(IUnitOfWork unitOfWork)
{
throw new NotImplementedException();
}
}
.