简体   繁体   English

EF代码优先模型上的自定义属性

[英]Custom attributes on EF code-first models

Currently using EF 6 in a new project. 当前在新项目中使用EF 6。 I've been using EF for sometime now, so am pretty familiar with it - at the very least as the average user of it. 我已经使用EF一段时间了,所以对它非常熟悉-至少是它的普通用户。

We are looking to split storage of data between SQL (eventually Azure SQL) and Azure Table Storage. 我们正在寻求在SQL(最终是Azure SQL)和Azure表存储之间拆分数据存储。

The reason for the split is some of the data on an entity just isn't suitable for a relational database. 拆分的原因是实体上的某些数据不适合关系数据库。 For example, we have some clients that prefer contact's to have properties A,B,C,D and another client prefers to have F,G,H,I,J,K,L - so it would make more sense to store this part of the data in a NoSql solution so we're not constraining ourselves, rather than adding dozens of columns in a table to handle varying requirements on that model. 例如,我们有一些客户更喜欢联系人具有属性A,B,C,D而另一个客户更喜欢具有F,G,H,I,J,K,L因此存储这一部分会更有意义NoSql解决方案中的数据,因此我们不限制自己,而是在表中添加数十列以处理对该模型的各种要求。

We're currently, in the new build, serializing/deserializing these sets of data which is ok, though not ideal. 目前,在新版本中,我们可以对这些数据集进行序列化/反序列化,这虽然不理想,但却可以。 Especially given it can be expensive performing this task on every read/write. 特别是考虑到在每次读/写时执行此任务可能会很昂贵。

So - that leads me to my question. 所以-这使我想到了我的问题。 (no code to show at this time) (目前没有代码显示)

I figured I would be able to decorate specific properties on some data models with a custom attribute, such as [NoSqlStore] and then react to these. 我认为我可以使用自定义属性(例如[NoSqlStore]来修饰某些数据模型上的特定属性,然后[NoSqlStore]做出反应。 I can, for example, override the SaveChanges() method in EF to save data to the appropriate table store should any property on the entity contain the attribute. 例如,如果实体上的任何属性包含该属性,我都可以覆盖EF中的SaveChanges()方法以将数据保存到适当的表存储中。

The hard part, at least what I'm struggling with at the moment, is how to handle reads from the database. 困难的部分是如何处理数据库中的读取,这至少是我目前正在努力解决的问题。 I would, ideally, like to be able to listen for (or override) something in EF that is fired when data is being fetched. 理想情况下,我希望能够侦听(或覆盖)EF在获取数据时触发的某些内容。 Is there such an event/method built into EF for this? EF是否内置了此类事件/方法? I figure if i can intercept EF when it's populating my model I can then react to any attribute decoration. 我认为在填充模型时是否可以拦截EF,然后可以对任何属性修饰做出反应。

In EF6 you can use the command interception mechanism where the interceptor is invoked each time the command is being executed. 在EF6中,可以使用命令拦截机制,每次执行命令时都会调用拦截器。 You can also modify results if needed (might be a bit cumbersome though). 您还可以根据需要修改结果(尽管可能有点麻烦)。 This article is a good starting point. 本文是一个很好的起点。 Another way to go about it is to look at the ObjectContext.ObjectMaterialized event and populate properties that are not populated by EF in the handler for this event. 解决该问题的另一种方法是查看ObjectContext.ObjectMaterialized事件,并在事件的处理程序中填充EF未填充的属性。

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

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