我如何检查EntityTypeConfiguration< T>的成员配置。实例? [英] How do I examine the member configurations of an EntityTypeConfiguration<T> instance?
问题描述
我正在使用Entity Framework Code First和从EntityTypeConfiguration继承的映射类。我这样做是为了封装使用Code First fluent API来配置实体的用法。
I'm using Entity Framework Code First with map classes inheriting from EntityTypeConfiguration. I do this to encapsulate my use of the Code First fluent API for configuring entities.
我希望能够检查在这些类中进行的配置设置,以便我可以在集成测试中应用其中的一些。我正在使用AutoFixture快速创建实体,最终我想找到一种方法来进行一些使用EntityTypeConfiguration类内部配置的自定义。
I would like to be able to examine the configuration settings made in these classes, so that I can apply some of them in my integration testing. I'm using AutoFixture to create entities quickly, and ultimately I want to figure out a way to make some customizations that consume the configurations inside of my EntityTypeConfiguration classes.
但是首先,我需要弄清楚如何将它们拔出...
But first, I need to figure out how to pull them out...
这里有一个用例:
public class Widget { public string Name { get; set; } }
public class WidgetMap : EntityTypeConfiguration<Widget> {
this.Property(w => w.Name).HasMaxLength(10);
}
我该如何执行以下伪代码:
How do I do something like this pseudo-code:
public Widget GetWidgetHonoringStringLengthConstraints(WidgetMap map) {
var w = new Widget();
int maxLength = map.GetProperty(p => p.Name).GetMaxLength(); //MAGIC
string name = new Guid().SubString(0, maxLength);
w.Name = name;
return w;
}
推荐答案
我收到了Arthur的回复实体框架Codeplex讨论中的维克斯。
I received a reply from Arthur Vickers in the Entity Framework Codeplex Discussions.
从本质上讲,他告诉我,我在树错了树,因为从设计上讲,他们不希望从常规公共表面检查配置类,因为这样做会污染API,并试图找到诸如字符串的最大长度之类的内容通常会告诉您整个故事,但不是整个故事(最终的最大长度限制可能来自多种约定,包括默认设置),这可能并不总能给您答案
Essentially, he told me I'm barking up the wrong tree, because, by design, they didn't want the configuration classes to be inspected from the normal public surface - the idea being that it would pollute the API and trying to find something like the max length of a string would often tell you the story, but not the whole story (the ultimate max length restriction may have come from several conventions, including a default setting), which might not always give you the answer you are really after.
他建议在构建模型后通过元数据工作区可以这样访问:
He recommended getting the metadata from the model after being built, through the MetadataWorkspace which can be accessed like this:
((IObjectContextAdapter)myDbContext).ObjectContext.MetadataWorkspace
我还没有追求实现,但是我将其标记为答案,直到有人提交了另一个答案(之前的一个例子)我可以解决这个问题,或者其他选择)。
I haven't pursued implementing this yet, but I'll mark this as the answer until someone submits another answer (either an example of this before I get around to it, or another option).
这篇关于我如何检查EntityTypeConfiguration< T>的成员配置。实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!