1

Trying to have a model with key which is string but in database will be represented as byte[].

Is there any way i can do it?

1 Answer 1

3

There is no direct translation from string to a byte array. You have to specify in what encoding the byte array will represent the string.

You can add a non-mapped wrapper property (TheStringValue below) that uses a specific encoding to map the string to bytes and vice versa:

public class MyEntity
{
    public byte[] StringBytes { get; set; }

    [NotMapped]
    public string TheStringValue
    {
        get
        {
            return Encoding.UTF8.GetString(StringBytes);
        }
        set
        {
            StringBytes = Encoding.UTF8.GetBytes(value);
        }       
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

[NotMapped] - NotMapped attribute can be applied to properties of a class. Default Code-First convention creates a column for all the properties which includes getters and setters. NotMapped attribute overrides this default convention. You can apply NotMapped attribute to a property which you do NOT want to create a column in a database table for. more info

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.