简体   繁体   English

C#实体框架:创建和保存(抽象类)

[英]C# Entity Framework: create and save (abstract class)

I have an existing project where I need to create some new instances of a class and save them to a database. 我有一个现有项目,需要在其中创建类的一些新实例并将其保存到数据库中。 The project uses Entity Framework, which I am not really familiar with. 该项目使用了我不太熟悉的实体框架。

I need to grab a set of items from a database that is of type CLASS A (abstract class). 我需要从类型为CLASS A(抽象类)的数据库中获取一组项目。 Since I cannot create instances of abstract classes, I created CLASS B that inherits from CLASS A. 由于无法创建抽象类的实例,因此创建了从CLASS A继承的CLASSB。

But, when I try to pull the CLASS A records from DB and return them as CLASS B items, the system throws an error 但是,当我尝试从数据库中提取CLASS A记录并将其作为CLASS B项目返回时,系统抛出错误

The entity type CLASS B is not part of the model for the current context 实体类型CLASS B不是当前上下文模型的一部分

So, I assume CLASS B must be mapped against CLASS A somehow? 因此,我认为必须以某种方式将B类映射到A类? But I'm not sure how? 但我不确定如何?

For mapping objects, you can use AutoMapper (at least that is what I always use for mapping objects from A <-> B). 对于映射对象,可以使用AutoMapper(至少我一直使用它来映射A <-> B中的对象)。 It's pretty easy. 很简单 https://github.com/AutoMapper/AutoMapper/wiki/Getting-started https://github.com/AutoMapper/AutoMapper/wiki/入门

Further, I'm not sure, but I don't think you can't use inheritance when it comes to Entity framework classes. 此外,我不确定,但是对于实体框架类,我不认为您不能使用继承。 You should just make 2 seperate classes. 您应该只做2个单独的类。 (So probably a classB with the same fields as classA, but you can also add/remove fields as much as you want and fill them up in your mapping). (因此,一个classB可能具有与classA相同的字段,但您也可以根据需要添加/删除任意数量的字段并将其填充到映射中)。

I hope the answer is any helpfull 我希望答案对您有帮助

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

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