简体   繁体   English

实体框架ID属性

[英]Entity Framework ID properties

I have an third party class model (that can't be modified) and I need to persist it using EF. 我有一个第三方类模型(无法修改),我需要使用EF进行持久化。 The problem is that some classes of that model don't have an ID property and don't have any property that can be used as keys for generated tables using Fluent API. 问题在于该模型的某些类不具有ID属性,并且不具有任何可用作Fluent API生成的表的键的属性。

I also thought to define ID properties in partial classes but partial classes can't be on different assemblies, so that solution is not feasible. 我还认为要在部分类中定义ID属性,但是部分类不能位于不同的程序集中,因此该解决方案不可行。 Reflection cross my mind but I don't think can be possible. 我脑海中浮现出思考,但我认为不可能。

There is a way (using Fluent API or other technique) to add properties (auto incremental for example) to an existence model that can't be modified? 有一种方法(使用Fluent API或其他技术)将属性(例如,自动增量)添加到无法修改的存在模型中?

Unless the 3rd party class is sealed you should be able to use it as a base class, and derive a more friendly class from it. 除非sealed了第三方阶级,否则您应该能够将其用作基类,并从中衍生出更友好的阶级。 For instance: 例如:

public class Foo //3rd party class
{ ... }

public class myFoo : Foo
{
    public long FooId {get; set;}
}

If it IS sealed you can still write a wrapper around it 如果sealed您仍然可以在其周围写一个包装纸

public sealed class Foo //3rd party sealed class
{ ... }

public class FooWrapper
{
    public long FooId {get; set;}
    public Foo InnerFoo {get; set;} 
}

In either case, you can then persist your custom object (the derived class or the wrapper) to your DB and then extract the original Foo whenever you desire. 无论哪种情况,您都可以将自定义对象(派生类或包装器)持久保存到数据库中,然后在需要时提取原始Foo

EDIT Based on your comment, you could also investigate using Composite Keys. 编辑根据您的评论,您还可以使用复合键进行调查。 Frankly, I've never used them in EF, so I wouldn't even really know where to begin telling you about them, but they may be a better fit for your specific needs. 坦白说,我从未在EF中使用过它们,所以我什至不知道从哪里开始向您介绍它们,但是它们可能更适合您的特定需求。

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

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