EntityFramework中几种操作小结

时间:2022-05-13 18:06:09

目前项目中使用到的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的封装