Entity framework 从我的POCO类中分离实体框架
通过迭代从EntityBase继承的任何实体并将它们添加到我的上下文中,我正在动态创建我的DbContext:Entity framework 从我的POCO类中分离实体框架,entity-framework,linq-expressions,Entity Framework,Linq Expressions,通过迭代从EntityBase继承的任何实体并将它们添加到我的上下文中,我正在动态创建我的DbContext: private void AddEntities(DbModelBuilder modelBuilder) { var entityMethod = typeof(DbModelBuilder).GetMethod("Entity"); foreach (var assembly in AppDomain.CurrentDomain.Ge
private void AddEntities(DbModelBuilder modelBuilder)
{
var entityMethod = typeof(DbModelBuilder).GetMethod("Entity");
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
var entityTypes = assembly.GetTypes()
.Where(x => x.IsSubclassOf(typeof(EntityBase)) && !x.IsAbstract);
foreach (var type in entityTypes)
{
dynamic entityConfiguration = entityMethod.MakeGenericMethod(type).Invoke(modelBuilder, new object[] { });
EntityBase entity = (EntityBase)Activator.CreateInstance(type);
//Add any specific mappings that this class has defined
entity.OnModelCreating(entityConfiguration);
}
}
}
这样,我可以有许多名称空间,但在我的基本名称空间中只有一个通用存储库,在任何地方都可以使用。此外,在使用多个名称空间的应用程序中,基本存储库已经设置为使用所有加载名称空间中的所有实体。我的问题是,我不想让EntityFramework.dll成为公司中每个命名空间的依赖项。因此,我调用ModelCreating并将EntityTypeConfiguration传递给类,以便它可以添加任何映射。这很好,下面是我如何添加映射来告诉模型我的“Description”属性来自一个名为“Descriptor”的列:
类小部件。。。{
模型创建时的公共覆盖无效(动态实体)
{
System.Linq.Expressions.Expression tmp=
x=>x.描述;
entity.Property(tmp).HasColumnName(“描述符”);
}
好的是,我的实体类没有对EF的引用,这个方法只被调用一次,当上下文被创建时,如果我们放弃EF并在将来转到其他对象,我的类中不会有所有特定于EF的属性
问题是,它太难看了。我如何让模型知道列映射和键,而不是创建这些
表达式,以便在我的poco类中无需硬编码引用EF就可以映射属性?您可以定义自己的属性,并使用它们来控制OnMo中的配置delCreating()
。您应该能够在一个linq查询中获得(使用反射)列映射所需的所有详细信息,第二个查询用于创建键
public class DatabaseNameAttribute : Attribute
{
private readonly string _name;
public DatabaseNameAttribute(string name)
{
_name = name;
}
public string Name
{
get
{
return _name;
}
}
}
public class KeySequenceAttribute : Attribute
{
private readonly int _sequence;
public KeySequenceAttribute(int sequence)
{
_sequence = sequence;
}
public int Sequence
{
get
{
return _sequence;
}
}
}
[DatabaseName("BlogEntry")]
public class Post
{
[DatabaseName("BlogId")]
[KeySequence(1)]
public int id { get; set; }
[DatabaseName("Description")]
public string text { get; set; }
}
您可以用一种更优雅的方式实现通用的repo模式,请查看@sza-这没有提到如何添加映射,而不在整个过程中包含EF引用。我们已有L2的映射,这些映射已经存在,并且只使用系统名称空间,因此我认为重用它们会很好地工作。我唯一关心的是,我无法轻松模拟EF的映射设置的所有功能。但我想这会让我在大部分方面达到目的。谢谢。
public class DatabaseNameAttribute : Attribute
{
private readonly string _name;
public DatabaseNameAttribute(string name)
{
_name = name;
}
public string Name
{
get
{
return _name;
}
}
}
public class KeySequenceAttribute : Attribute
{
private readonly int _sequence;
public KeySequenceAttribute(int sequence)
{
_sequence = sequence;
}
public int Sequence
{
get
{
return _sequence;
}
}
}
[DatabaseName("BlogEntry")]
public class Post
{
[DatabaseName("BlogId")]
[KeySequence(1)]
public int id { get; set; }
[DatabaseName("Description")]
public string text { get; set; }
}