问题
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) ?
回答1:
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.
来源:https://stackoverflow.com/questions/7886672/how-to-ignore-entity-in-entity-framework-code-first-via-setup