gpt4 book ai didi

entity-framework - 如何更改EntityFramework中自动生成的 "Discriminator"列?

转载 作者:行者123 更新时间:2023-12-05 00:34:24 25 4
gpt4 key购买 nike

我正在研究一些通过EF4.3使用单表继承的代码。

有一个名为“用户”的实体和另一个名为“Admin”的实体。管理员继承自用户。

用户类

public class User
{
public int Id {get;set;}
public string Username {get;set;}
}

管理类
public class Admin : User { }

EF用 Discriminator列生成了数据库表。添加 Admin记录后, Discriminator="Admin"和用户记录将具有 Discriminator="User"

我的问题是,如果我想将 Discriminator放入和 User中,如何更新 Admin列?

我尝试将一种对象类型转换为另一种对象类型,然后使用EF保存。但这不会更改“鉴别器”列。我该如何更改?

谢谢你的帮助。

最佳答案

对象永远无法更改其类型。如果打算更改用户的“管理员”设置(合理的),则应使用属性/属性(而不是类型名称)进行更改。

例如,您可能在User对象和Administrator对象之间建立了关联,而不是想要用User子类型替换Administrator对象。

I wrote about this idea in an old blog post:

One of the mental barriers that you have to get over when designing a good object relational mapping is the tendency to think primarily in object oriented terms, or relational terms, whichever suits your personality. A good object relational mapping, though, incorporates both a good object model and a good relational model. For example, let’s say you have a database with a table for People, and related tables for Employees and Customers. A single person might have a record in all three tables. Now, from a strictly relational point of view, you could construct a database VIEW for employees and another one for customers, both of which incorporate information from the People table. When using a one VIEW or the other, you can temporarily think of an individual person as "just" an Employee or "just" a Customer, even though you know that they are both. So someone coming from this worldview might be tempted to do an OO mapping where Employee and Customer are both (direct) subclasses of Person. But this doesn’t work with the data we have; since a single person has both employee and customer records (and since no Person instance can be of the concrete subtype Employee and Customer simultaneously), the OO relationship between Person and Employee needs to be composition rather than inheritance, and similarly for Person and Customer.



要直接回答您的问题,无法使用EF更改此列。您当然可以用直接SQL来完成。但是出于上述原因,我建议您更改此设计。

关于entity-framework - 如何更改EntityFramework中自动生成的 "Discriminator"列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10728061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com