Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 307
Marc Planas Avatar asked Dec 08 '25 22:12

Marc Planas


1 Answers

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.

like image 183
bruno.almeida Avatar answered Dec 10 '25 10:12

bruno.almeida



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!