entity framework not working on table without identity column

.net c# entity-framework sql

Question

I have the table below.

create table tbl
(
    id int identity(1,1),
    val varchar(100)
)

Now that I've mapped items to this table using Entity Framework, everything works; but, when I alter the table definition as follows:

create table tbl1
(
    id int,
    val varchar(100)
)

This table's objects are not mapped by Entity Framework. Any insight on why this is occurring would be much appreciated.

1
7
10/16/2012 5:08:56 AM

Accepted Answer

A Primary Key is necessary for Entity Framework to create a model from the database. The non-nullable columns will be used as a concatenated primary key if a table's primary key is missing, and the entity will be read-only.

In order to enable the creation of an Entity, your initial table's identity declaration makes the id column non-nullable. When you added that table, you ought to have received the following message:

"The table/view 'tbl1' does not have a primary key defined. The key has been inferred and the definition was created as a read-only table/view."

However, there isn't a non-nullable field in your second table, therefore EF can't create an Entity for it. When you attempt to add it, you'll see this message:

"The table/view 'tbl1' does not have a primary key defined and no valid primary key could be inferred. This table/view has been excluded. To use the entity, you will need to review your schema, add the correct keys, and uncomment it."

8
10/16/2012 4:56:11 AM

Popular Answer

In order to differentiate between two entries in a table, entity frameworks often need an ID/Key discriminator, which need not be a primary key constraint, a unique key constraint, or an identity at the database layer. However, the entity framework should be able to uniquely identify a record and separate it apart from other records with the aid of this discriminator, which might be a column or collection of columns. This means that you must declare a discriminator of this kind in your entity class at the C# layer.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow