如何通过设置首先忽略实体框架代码中的实体 [英] How to ignore entity in Entity Framework Code first via setup

查看:103
本文介绍了如何通过设置首先忽略实体框架代码中的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有4个类:

  public class Component {} 
public class SubComponent1:Component {}
public class SubComponent2:Component {}
public class Container:Component {
public List< Component>组件{get; set;}
}

我不想在数据库上存储SubComponent2。我想在整个应用程序中使用它作为普通的POCO,只希望在尝试保存到数据库时忽略它。
到目前为止我已经尝试的是在我的DbContext OnModelCreating方法中放置Ignore:

  dbModelBuilder.Ignore< SubComponent2>(); 

然后尝试保存一些包含SubComponent2的结构,希望SubComponent2将被忽略,因此没有保存。
所以基本上是这样的:

  var someContainer = new Container {components = new List< Component> {
new SubComponent1(),new SubComponent2()
};
context.Containers.Add(someContainer);

,希望只有具有SubComponent1的Container才能访问数据库。
我所得到的是


找不到EntityType'SubComponent2'的映射和元数​​据信息


我知道我可以简单地手动删除所有SubComponent2-s,然后将容器添加到上下文中,然后保存然后重新连接SubComponent2-s,但这似乎太多了当我希望实体框架能够解决这个为我的时候,在更大的结构上的开销。



你知道有什么好的方法(可能在dbModelBuilder设置中有一些变化在我的DbContext中)?

解决方案

我认为这是不受支持的。您可以忽略派生实体,因此它不被映射,但是您不能在保存期间在导航属性中使用它。我没有测试它,但我几乎肯定,EF没有逻辑跳过继承映射中被忽略的实体,因为被忽略的实体根本不属于持久集合。


Lets say i have 4 classes:

public class Component {}
public class SubComponent1 : Component {}
public class SubComponent2 : Component {}
public class Container : Component { 
  public List<Component> components { get; set;}
}

And I don't want to store SubComponent2 on database. I want to use it throughout application as normal POCO, only want it to be ignored when trying to save to database. What I have tried so far was to put Ignore for it in my DbContext OnModelCreating method:

dbModelBuilder.Ignore<SubComponent2>();

and then tried to save some structure containing also SubComponent2 on database hoping that SubComponent2 would simply be ignored, and thus not saved. So basically something like:

var someContainer = new Container{ components = new List<Component>{ 
  new SubComponent1(), new SubComponent2() 
};
context.Containers.Add(someContainer);

and hoped only Container with SubComponent1 would get to database. What I got instead was

Mapping and metadata information could not be found for EntityType 'SubComponent2'

I know I could simply manually remove all SubComponent2-s, then add Container to context, save and then reattach SubComponent2-s somehow, but that seems like too much overhead on bigger structures when I hoped entity framework could be able to solve this "for me"

Do you know of any nice way around this (probably some change in dbModelBuilder setup in my DbContext) ?

解决方案

I think this is unsupported at the moment. You can ignore derived entity so it is not mapped but you cannot use it in navigation properties during saving. I didn't test it but I'm almost sure that EF has no logic to skip ignored entities in inheritance mapping because ignored entity simply doesn't belong to persisted collection.

这篇关于如何通过设置首先忽略实体框架代码中的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆