Custom Type as Primary Key

2019-07-04 21:46发布

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?

1条回答
太酷不给撩
2楼-- · 2019-07-04 22:28

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.

查看更多
登录 后发表回答