简体   繁体   中英

Entity Framework ID properties

I have an third party class model (that can't be modified) and I need to persist it using 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.

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. 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?

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. 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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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