0

I'm using Entity Framework to map some tables, but I can't do this unless I declare some column as the primary key.

The problem here is that my table in my database don't have a primary key and has millions of rows. I don't have permission to create a new Id column.

[Table("MYTABLE")]
public class myTable
{
    [Column("NUMX")]
    public virtual string NumX { get; set; }

    [Column("NAME")]
    public virtual string Name { get; set; }

    [Column("AGE")]
    public virtual int AGE { get; set; }
}

Obs: If I add the [Key] attribute to some column like Age, it works, but returns the wrong data.

Is there some way to omit the primary key?

5
  • 1
    You can make a composite key from all the columns. Commented Apr 12, 2018 at 16:57
  • 1
    Please refer these SO questions: stackoverflow.com/questions/3996782/… , stackoverflow.com/questions/15381233/… Commented Apr 12, 2018 at 17:00
  • 3
    Any "normal" data table ought to have a primary key - why would you leave that out in the first place? EF needs something to uniquely identify each row - the exact job of the primary key! So don't try to find ways "around" this - instead, embrace the primary key and add one to your tables! (even if it has millions of rows already) Commented Apr 12, 2018 at 17:04
  • Is NUMX unique? Commented Apr 12, 2018 at 17:24
  • The problem is your data model not already having a primary key. Commented Apr 12, 2018 at 18:26

2 Answers 2

2

I Figured out the problem. Composite Keys works for me: eg: In my Context I defined some keys, not only one, but three keys:

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        **//Here is the secret**
        modelBuilder.Entity<MyModel>().HasKey(x => new { x.NumX, x.Name,x.Age});
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Entity Framework requires a primary key unlike SQL.

EF use the primary key to uniquely identify rows (for example when you use .Find() or to perform update operations).

Infact not having a primary key remember a SQL VIEW, where you can only read data.

If any of the columns uniquely identify a certain row set it as a primary key (it can't be NULL) also if in Sql it isn't a key. Otherwise if the combination of the columns are uniquely, create a composite key with these columns.

Remember that you should have a primary key in the 99% of cases, when you don't have a primary key you should stop and think if it make sense.

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.