如何告诉EF忽略数据库中的列? [英] How do I tell EF to ignore columns from my database?

查看:683
本文介绍了如何告诉EF忽略数据库中的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从SQL Server数据库中建立EF(v4.0.30319)数据模型。每个表都有通过数据库触发器填充的已创建已更新字段。

I'm building my EF (v4.0.30319) data model from my SQL Server database. Each table has Created and Updated fields populated via database triggers.

此数据库是ASP.NET Web API应用程序的后端,我最近发现了一个问题。问题在于,由于在传递给api端点的模型中没有填充 Created Updated 字段,因此它们是以 NULL 的形式写入数据库。这会覆盖数据库中那些属性的所有值。

This database is the backend of a ASP.NET Web API application and I recently discovered a problem. The problem is, since the Created and Updated fields are not populated in the model passed into the api endpoint, they are written to the database as NULL. This overwrites any values already in the database for those properties.

我发现我可以编辑EF数据模型,只需从实体中删除这两列即可。它有效,日期时间不会被 NULL 覆盖。但这会导致另一个不那么严重但更烦人的问题……我的数据模型有一堆包含这些属性的表,所有表都需要通过删除这两列来进行更新。

I discovered I can edit the EF data model and just delete those two columns from the entity. It works and the datetimes are not overwritten with NULL. But this leads to another, less serious but more annoying, problem... my data model has a bunch of tables that contain these properties and all the tables need to be updated by removing these two columns.

是否有一种方法可以让EF忽略整个数据模型中实体中的某些列而无需手动删除它们?

Is there a way to tell EF to ignore certain columns in entities across the entire data model without manually deleting them?

推荐答案

据我所知,没有。从数据库生成模型将总是从数据库表中创建所有字段。好吧,只要它具有主键即可。

As far as I know, no. Generating the model from the database is going to always create all of the fields from the database table. Well, as long as it has a primary key it will.

可以仅更新所需的字段,即不包括 Created和创建和更新方法中的已更新字段。不过,我不得不说,如果那时这些字段甚至不在模型中,那会更好。您可能会在某一时刻看到模型上的那些字段,而忘记了它们不会持久化到数据库中。

It is possible to only update the fields that you want i.e. don't include the "Created" and "Updated" fields in your create and update methods. I'd have to say though, that I'd think it'd be better if those fields didn't even exist on the model at that point. You may at one point see those fields on the model and not remember that they won't get persisted to the DB.

您可能希望在调用create()和update()方法时将日期时间插入这些字段中。然后,您可以抛开触发器。您显然希望对所有数据库操作使用类库,因此此功能将集中在一个地方。要保持它的美观和整洁,您知道吗?

You may want to look into just inserting the datetimes into those fields when you call your create() and update() methods. Then you could just ditch the triggers. You'd obviously want to use a class library for all of your database operations so this functionality would be in one place. To keep it nice and neat, you know?

这篇关于如何告诉EF忽略数据库中的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆