码迷,mamicode.com
首页 > 其他好文 > 详细

EntityFramework中几种操作小结

时间:2015-04-19 16:10:45      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

目前项目中使用到的EntityFramework中几种操作小结,先标记下。没有详细介绍,后续有空的话再补充一些并完善一下。

?

列中加入RowVersion时间戳

????public class Product
????{
????????public int Id { get; set; }
????????public string Name { get; set; }

????????
[Timestamp]
????????public Byte[] RowVersion { get; set; }
????}

?

查询中加入RowVersion比较

  1. 编写扩展函数

????internal static class EntityFrameworkHelper
????{
????????public static int Compare(this byte[] b1, byte[] b2)
????????{
????????????throw new NotImplementedException("This is only for linq to sql");
????????}
????}

  1. 用扩展函数查询

????db.Products.Where(i => i.RowVersion.Compare(version) > 0).ToList();

?

乐观锁

????public class Product
????{
????????public int Id { get; set; }
????????public string Name { get; set; }

????????[Timestamp,
ConcurrencyCheck]
????????public Byte[] RowVersion { get; set; }
????}

?

带过滤条件的DBSet

  1. 添加Can a DbContext enforce a filter policy?一文中的FilteredDbSet,
  2. 修改DbContext,使用FilteredDbSet替换默认的DbSet

????public IDbSet<Product> Products { get { return new FilteredDbSet<Product>(this, i=>i.IsRemoved == false); } }

?

标记删除

继承FilteredDbSet,重载其删除函数

????public interface IflagRemoveObject
????{
????????bool IsRemoved { get; set; }
????}


????class FlagRemoveDbSet<T> : FilteredDbSet<T> where T : class, IflagRemoveObject
????{
????????public override T Remove(T entity)
????????{
????????????entity.IsRemoved = true;
????????????return entity;
????????}
????}

?

单元测试:

  1. 打桩DbSet:FakeDbSet
  2. DbContext的封装

EntityFramework中几种操作小结

标签:

原文地址:http://www.cnblogs.com/TianFang/p/4439215.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!