简体   繁体   English

在实体框架中使用嵌套类

[英]Using Nested Classes with Entity Framework

I've tried to do this in the designer, but I wasn't able to figure it out.我试图在设计师中做到这一点,但我无法弄清楚。 Is it possible to persist nested classes using Entity Framework?是否可以使用 Entity Framework 持久化嵌套类?

Note: I am just curious whether this is possible or not.注意:我只是好奇这是否可能。 I can't think, at this point, if there would ever be a reason to do this, but it might be nice to know how if it is possible.在这一点上,我不知道是否有理由这样做,但如果有可能知道如何做可能会很好。

Example:例子:

public class NormalClass
{
    public class NestedClass { }
}

Update:更新:

Danny Varod had a good idea for how to accomplish this. Danny Varod 对如何实现这一点有一个好主意。 When I have some spare time, I'm going to try it out, and I'll post the results on here, unless someone else gets to it first.当我有空闲时间时,我会尝试一下,我会在这里发布结果,除非其他人先得到它。

A nested class in .NET is basically the same as a class within another level of namespace (accept for the fact the inner class can access private parts of outer class, as Ladislav Mrnka pointed out - you could use internal instead of private to get around this), there is no change in behaviour (unlike in Java), so there is not much point in using nested classes. A nested class in .NET is basically the same as a class within another level of namespace (accept for the fact the inner class can access private parts of outer class, as Ladislav Mrnka pointed out - you could use internal instead of private to get around this ),行为没有变化(与 Java 不同),因此使用嵌套类没有多大意义。

You can define sub objects using complex properties or using a navigation properties, however, complex properties have limited capabilities (no navigation properties or keys in them) and neither are created as nested classes.您可以使用复杂属性或导航属性定义子对象,但是,复杂属性的功能有限(其中没有导航属性或键),并且两者都不是嵌套类。

To force EF to use nested classes, you could try creating the classes yourself, then mapping them either with a Code-First approach or by cancelling the auto-creation of the class and writing them yourself (or changing the.tt file to created classes nested) and then editing the.emdx as an xml to map entity to a different class.要强制 EF 使用嵌套类,您可以尝试自己创建类,然后使用 Code-First 方法映射它们,或者取消 class 的自动创建并自己编写它们(或将 .tt 文件更改为创建的类嵌套),然后将 .emdx 编辑为 xml 到 map 实体到不同的 class。

EF classes are declared partial , so you can add whatever you want to them. EF 类被声明为partial ,因此你可以向它们添加任何你想要的东西。

Note that the inner-class's properties won't be persisted to the DB, if you want that, use a navigation property instead.请注意,内部类的属性不会持久保存到数据库中,如果需要,请改用导航属性。

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

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