zoukankan      html  css  js  c++  java
  • EntityFramework中几种操作小结

    目前项目中使用到的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的封装
  • 相关阅读:
    Mysql 命令行连接
    linux下安装MongoDB数据库
    SVN 提交常见报错及解决方案
    解决 SVN Skipped 'xxx' -- Node remains in conflict
    linux svn 切换用户
    SQL基础语法
    yml
    搭建笔记(1)
    文件上传MultipartFile
    18.线程池
  • 原文地址:https://www.cnblogs.com/TianFang/p/4439215.html
Copyright © 2011-2022 走看看