Marc Planas
Marc Planas

Reputation: 125

Custom Type as Primary Key

I'm currently working with EF6 code-first on Visual Studio 2015. I'm working on a database that I want to use user-defined types as primary keys.

This is a simple example of what I want:

public class ObjectIdType
{
    public string id { get; set; }
}

This will be the user-defined type.

public class ClasseProva
{

    [Key][DatabaseGenerated(DatabaseGeneratedOption.None)]
    public ObjectIdType Id { get; set; }

}

And this will be the entity where I want to use my custom type as PrimaryKey.

When I do this like the example an error occur when I try to create the controller, the error is: The property type is not a valid key type.

I found that you just can use scalar types as PK, but i'm wondering if I make my ObjectIdType inherit from String it will work? I tried to do it like this (obviously don't work):

public class ObjectIdType : String
{
    public string id { get; set; }
}

Is there any way to define my ObjectIdType as inheritance from String? Or there is any way to make a user-defined type a PK?

Upvotes: 3

Views: 468

Answers (1)

bruno.almeida
bruno.almeida

Reputation: 2896

Is there any way to define my ObjectIdType as inheritance from String?

No. String is sealed.

Or there is any way to make a user-defined type a PK?

Not 100% sure, but i think you can not do that.

Upvotes: 3

Related Questions