1

i have a existing table with a primary key over 3 columns (1 varchar and 2 integer). How can i tell the entity framework to use this "key". Is it possible using the modelBuilder, attributes or is there another way ?

thanks!

1 Answer 1

3

In fluent api you must use anonymous type:

modelBuilder.Entity<YourType>()
            .HasKey(e => new 
                {
                    e.VarChar,
                    e.Int1,
                    e.Int2
                });

Other way is using data annotations:

public class YourType
{
    [Key, Column(Order = 0)]
    public string VarChar { get; set; }
    [Key, Column(Order = 1)]
    public int Int1 { get; set; }
    [Key, Column(Order = 2)]
    public int Int2 { get; set; }
}

In both scenarios order of columns is important. Once you try to use DbSet<YourType>.Find you will have to supply keys in the same order. EF also uses order internally.

Sign up to request clarification or add additional context in comments.

Comments

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.