【发布时间】:2018-04-11 11:39:00
【问题描述】:
我在实体框架中使用动态过滤器。它是EntityFramework.DynamicFilters 中的DBModelBuilder.Filter 扩展方法。当我修改要过滤掉的实体时,在使用相同数据库上下文的下一个请求中,它在浏览导航集合时仍然可见。
这是正常行为吗?有什么方法可以在不改变应用程序中更新和读取数据的方式的情况下修复它?
以下是显示我的问题的示例控制台应用程序。
当我使用 ProductDbContext 的不同实例通过类别间接读取产品时,或者当我直接从同一数据库上下文中读取类别时,它工作正常。
实体和数据库上下文:
public enum Status
{
New = 0,
Used = 1
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public Status Status { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
public override string ToString()
{
return $"Id = {Id}, Name = {Name}, Status = {Status.ToString()}";
}
}
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
public class ProductDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Filter("OnlyNewProducts", (Product p) => p.Status == Status.New);
}
}
类别:
-------------------
| Id | Name |
-------------------
| 3 | Category 1 |
-------------------
产品:
----------------------------------------
| Id | Name | Status | CategoryId |
----------------------------------------
| 3 | Product 1 | 0 | 3 |
----------------------------------------
显示我的问题的类:
class Program
{
static ProductDbContext ctx = new ProductDbContext();
static void Main(string[] args)
{
Read();
Modify();
Read();
}
private static void Modify()
{
var product = ctx.Products.FirstOrDefault(p => p.Name == "Product 1");
product.Status = Status.Used;
ctx.Entry(product).State = EntityState.Modified;
ctx.SaveChanges();
}
private static void Read()
{
var newProducts = ctx.Categories.FirstOrDefault(c => c.Name == "Category 1").Products.ToList();
foreach (var newProduct in newProducts)
{
Console.WriteLine(newProduct.ToString());
}
}
}
结果:
Id = 3, Name = Product 1, Status = New
Id = 3, Name = Product 1, Status = Used
不应显示具有“已使用”状态的更新实体。
【问题讨论】:
-
我在保存更改后通过调用
((IObjectContextAdapter)ctx).ObjectContext.Refresh(RefreshMode.StoreWins, product)找到了解决方法,但这不是我想要的。
标签: c# .net entity-framework filter dbcontext