简体   繁体   English

如何禁用Entity Framework中的属性自动化

[英]How to disable automapping of properties in Entity Framework

I've decided to use fluent mapping in Entity Framework. 我决定在Entity Framework中使用流畅的映射。 My intention was to map everyting by code without any atributes and auto mapping functions. 我的目的是通过代码映射每个代码而不使用任何属性和自动映射函数。 Best way I've found is class EntityTypeConfiguration, that I implement for each entity in my project. 我发现的最好方法是类EntityTypeConfiguration,我为项目中的每个实体实现。

Later I add property to one of my entity. 后来我将属性添加到我的一个实体中。 This property isn't needed to be persisted. 不需要保留此属性。 I've expected, that until I add mapping for this property, it will be ignored by database and persistence layer. 我曾预料到,在我为此属性添加映射之前,它将被数据库和持久层忽略。 Unfortunatly it doesn't work that way, and property is mapped. 不幸的是,它不起作用,并且属性被映射。 Only way is to use Ignore method or NotMapped attribute, but I don't want to do it explicitly. 唯一的方法是使用Ignore方法或NotMapped属性,但我不想明确地这样做。

Is there any way, to stop Entity Framework from automapping? 有没有办法阻止Entity Framework自动化? I've tried to remove all Conventions from DbModelBuilder, but it doesn't help. 我试图从DbModelBuilder中删除所有约定,但它没有帮助。

So far as I am aware, there is no other way around it. 据我所知,除此之外别无他法。 You need to use either Ignore() or [NotMapped] . 您需要使用Ignore()[NotMapped] I tend to prefer the former as it does not clutter up the model. 我倾向于选择前者,因为它不会使模型混乱。

Actually I have tried a lot of ways: - custom convention to remove mapped properties - removing all conventions 实际上我已经尝试了很多方法: - 删除映射属性的自定义约定 - 删除所有约定

But the easiest (and cleanest) way was to use reflection inside the mapping class and to disable all property mappings that weren't configured. 但最简单(也是最简洁)的方法是在映射类中使用反射并禁用所有未配置的属性映射。

The code for that (and also an usage example) is inside my public gist. 该代码(以及一个用法示例)在我的公开要点中。 https://gist.github.com/hidegh/36d92380c720804dee043fde8a863ecb https://gist.github.com/hidegh/36d92380c720804dee043fde8a863ecb

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM