How do you signify a primary key in EF Code First? - entity-framework

I am new to EF Code First. How do you go about representing that a variable in an object should be the primary key when it is peristed to a database table?

By default and by convention, if you have a column called ID or (EntityName)ID (e.g. CustomerID for an entity of type Customer), then that will be your primary key.
Otherwise, you need to use the [Key] attribute on another column.

Related

Generate one Id column included in composite Primary Keys in JPA, while one Id starts from 1 when the other Id column changes

The entity A has an OneToMany relation with the entity B. I would like to use a composite primary key for the entity B, where one of the columns is the same as the the primary key of the entity A and the second column should be generated. How can the second column be started from 1 whenever the the other involving column within the composite primary key changes?
I use Oracle data bank and could not find any solution.
Thanks in advance!

How to change primary key on a table using code first in entity framework

I have a table created by Entity Framework 6 Code first. It has the Id as a primary key. I would like to change this so that a guid property is the primary key instead. But I I keep getting this error "To change the IDENTITY property of a column, the column needs to be dropped and recreated". Can someone please show me what I need to do?

Violation of PRIMARY KEY constraint on linked record when add a record using the entity framework

I have a table called farmers. Each farmer has a country specified that is mandatory.
When I add a new farmer to the database using antity framework, I get a violation on the country table. It looks like the entity framework wants to add the country to the country table, but I only want the guid in my farmer table:
Violation of PRIMARY KEY constraint 'PK_Country'. Cannot insert
duplicate key in object 'dbo.Country'. The statement has been
terminated.
Can somebody advise me on what I'm doing wrong? here the code for the insert:
newFarmer.Guid = Guid.NewGuid();
ents.Farmer.AddObject(newFarmer);
ents.SaveChanges();
return newFarmer;
I even checked the state of the country and it says unchanged.
One possible solution is that Entity Framework doesn't understand that your entity primary key is also the identity and should be auto-incremented. I had the same problem in an application using EF 4.1 with database first. To solve the problem, I had to::
Make sure my entities primary key had a name "ID" (to avoid putting a decorator [Key] above my Model class.
Make sure the property option "Identity" of your database system (SQL Server in my case) is set to "Yes".
Then, my EF4.1 was able to do the insert and update of my entities.
Hope this helps!

Entity Framework Is it possible to add an ASSOCIATION between Primary Keys and a Foreign Key

I've got the following entities on my EDMX :-
These two entites were generated by Update Model From Database.
Now, notice how my country has the following primary key :-
Name & IsoCode
this is because each country is UNIQUE in the system by Name and IsoCode.
Now, with my States ... it's similar. Primary Key is :-
Name & CountryId
Each state is unique by name and per country.
Now, the Foreign Key for States is a CountryId. This is the sql :-
ALTER TABLE [dbo].[States] WITH CHECK ADD
CONSTRAINT [FK_States_Countries] FOREIGN KEY([CountryId])
REFERENCES [dbo].[Countries] ([CountryId])
ON UPDATE CASCADE
GO
ALTER TABLE [dbo].[States] CHECK CONSTRAINT [FK_States_Countries]
GO
Pretty simple stuff.
BUT EntityFramework doesn't like it :( It's assuming that i need to connect some properties from State entity to both primary key properties in the Country entity.
Is it possible to add an ASSOCIATION between Country and State on Country.CountryId <-> State.CountryId ... like i have mapped in my DB ?
Cheers ;)
In EF (3.5 and 4.0) FKs MUST point to Primary Keys.
But you appear to be attempting to point to a Candidate Key (i.e. [Countries].[CountryId]
I know that this is something the EF team are considering for the next version though :)
Hope this helps
Alex
For proper DB normalization, first thing is that primary keys must be only CountryId and StateId fields - the main Id fields for each table.
And ss I see from the description Name & IsoCode and Name & CountryId should be actually Unique keys, not primary.
Then the model class State should have a field:
public Country Country { get; set; }
Now EF have very good examples and since 4.3.1 + it fully supports Code first / DB first models, which I think will ease solving this.
EF 5 have more compatibility updates so I think it wont be a problem for legacy DB engines.

Composite primary keys which are also foreign keys in Entity Framework

If I have 2 tables 1 with a composite primary key where one of the keys is also a foreign key in another table:
Table 1:
A (PK, FK - maps to X in Table 2)
B (PK)
C
Table 2:
X (PK)
Y
Because A is both the PK in table 1 and FK in table 2, when I use EF to generate the entity model, I have both a Scalar AND a Navigation property for A in table 1. I cannot seem to remove A as a scalar (I think because it is a primary key).
The problem I am having is that if I create a table1Entity and set A's scalar property to a new value, A's navigation property will not be changed automatically (and vice versa).
Ideally I just want A to expose the navigation property - which is the way it behaves if A was not also part of the composite primary key anyway. Is there any way to achieve this?
Am I correct in assuming that Table1 derives from Table2? If so, I would do it like so:
(I'd also change the PK for both tables to the same name, since they probably have the same meaning - for the instance of this, I'll use the example ID)
First, create the model with the default relationships (I usually just import the two tables from the database)
In the designer, right click the base type, add inheritance, select the derived type.
Delete the one to zero or one association
Then, since the base type already has column ID, delete it from the derived type.
Go to table mapping for the derived type, and map the ID property to the ID of the table.
Well, not really. Create the view with schemabinding and create a clustered index on the view (SQL Server 2008 or later, earlier versions I'm not sure can do that). The clustered index will be recognised as a primary key, thus tricking EF(VS) into believing the view is a real table.
Have you expicity set the Ids of the composite key and referenced these in your configuration?
i.e
public class Table1
{
public Table2 A{get;set}
public int AId {get;set;}
public int BId {get;set;}
}
I assume you'll need something like:
HasKey(pc => new { pc.AId, pc.BId});
HasRequired(x => x.A).WithMany().HasForeignKey(x => x.AId);
Instead of mapping to table 1 directly, add a view to your database that's got all of table 1's fields, plus an extra copy of A (A2).
Then, map the scalar key to A2 and the nav key to A.
(You'll run into a problem where if you use a view, Visual Studio can't find a primary key; fix this by manually editing the XML of the edmx file and adding a <Key><PropertyRef ... /></Key> to the <EntityType> for table A)
I know - it's hacky and horrible... but hey - it works!