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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    You can make a composite key from all the columns. – Fran Apr 12 '18 at 16:57
  • 1
    Please refer these SO questions: https://stackoverflow.com/questions/3996782/entity-framework-table-without-primary-key , https://stackoverflow.com/questions/15381233/can-we-have-table-without-primary-key-in-entity-framework – vrluckyin Apr 12 '18 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) – marc_s Apr 12 '18 at 17:04
  • Is `NUMX` unique? – Bradley Uffner Apr 12 '18 at 17:24
  • The problem is your data model not already having a primary key. – Daxtron2 Apr 12 '18 at 18:26

2 Answers2

1

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});
    }
}
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.

Embri
  • 622
  • 3
  • 15