Entity Framework on primary key and is null - entity-framework

I need to map some external database, I can't modify the schema. But the tables don't have primary key but rather columns like Client_ID, Calendar_ID but they are not null and entity can map them, much worse is if these columns in few tables can be null, then Entity Framework throws an error that it can't be mapped.
My question is: can I somehow disable entity tracking and map these tables without primary key and with columns as null?
Or can I use code-first approach, does it let me to create and map class with no primary key and all columns as is null?

Entity Framework must have a key field in order to work. It doesn't have to be a true primary key in the database but it needs to be unique. If you have tables that have a nullable field and no true primary key and you can't modify the database then maybe Entity Framework isn't the best fit for this project. It might work if you never try and load the entities with the null values, but it will throw errors when you do (as you have noticed).

Related

Does Entity Framework Core have an option to use a default value of 0 instead of null for non existent references?

If I have an object called Project that has a property called Creator and creator is a complex type, EF will automatically use the value null if the Creator property has not been assigned. Is it possible to instead use 0 instead of null in the database fields?
No, that would break Foreign Key Constraints on the database side, since there wouldn't be a Creator row with a primary key of 0 for the Project row's foreign key to point to.
In a relational database, at least those that respect foreign key constraints, every relationship between rows is represented as a pair of primary, and foreign keys. The database is designed to enforce that a foreign key always points to a valid primary key. It will prevent you from updating a FK field to a value that doesn't exist in the PK field. It will also yell at you for trying to delete the row that contains the PK as long as the FK still points to it (unless cascade-delete is turned on, but that gets complicated).
In theory, Entity Framework could probably be forced in to trying to do what you want, but the database would reject it, and EF would almost certainly have issues trying to retrieve rows with the 0/null value in it if it is configured to include navigation properties.

How to persist an entity will null primary key

I am using EclipseLink JPA implementation. I need to persist an entity with null primary key. The key are generated by a trigger and therefore must always be null for new rows. Nothing can be changed in the database, so none of the #GeneratedValue options is suitable.
I tried #PrimaryKey(validation=IdValidation.NONE), but it does not help.
I always receive an error like:
Exception Description: Null or zero primary key encountered in UnitOfWork clone
Currently I am using a simple insert statement.
Could anyone suggest what to change to be able to use persist() method with new entities with null pk?
Thanks

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 and multi-tenancy database design

I am looking at multi-tenancy database schema design for an SaaS concept. It will be ASP.NET MVC -> EF, but that isn't so important.
Below you can see an example database schema (the Tenant being the Company). The CompanyId is replicated throughout the schema and the primary key has been placed on both the natural key, plus the tenant Id.
Plugging this schema into the Entity Framework gives the following errors when I add the tables into the Entity Model file (Model1.edmx):
The relationship 'FK_Order_Customer' uses the set of foreign keys '{CustomerId, CompanyId}' that are partially contained in the set of primary keys '{OrderId, CompanyId}' of the table 'Order'. The set of foreign keys must be fully contained in the set of primary keys, or fully not contained in the set of primary keys to be mapped to a model.
The relationship 'FK_OrderLine_Customer' uses the set of foreign keys '{CustomerId, CompanyId}' that are partially contained in the set of primary keys '{OrderLineId, CompanyId}' of the table 'OrderLine'. The set of foreign keys must be fully contained in the set of primary keys, or fully not contained in the set of primary keys to be mapped to a model.
The relationship 'FK_OrderLine_Order' uses the set of foreign keys '{OrderId, CompanyId}' that are partially contained in the set of primary keys '{OrderLineId, CompanyId}' of the table 'OrderLine'. The set of foreign keys must be fully contained in the set of primary keys, or fully not contained in the set of primary keys to be mapped to a model.
The relationship 'FK_Order_Customer' uses the set of foreign keys '{CustomerId, CompanyId}' that are partially contained in the set of primary keys '{OrderId, CompanyId}' of the table 'Order'. The set of foreign keys must be fully contained in the set of primary keys, or fully not contained in the set of primary keys to be mapped to a model.
The relationship 'FK_OrderLine_Customer' uses the set of foreign keys '{CustomerId, CompanyId}' that are partially contained in the set of primary keys '{OrderLineId, CompanyId}' of the table 'OrderLine'. The set of foreign keys must be fully contained in the set of primary keys, or fully not contained in the set of primary keys to be mapped to a model.
The relationship 'FK_OrderLine_Order' uses the set of foreign keys '{OrderId, CompanyId}' that are partially contained in the set of primary keys '{OrderLineId, CompanyId}' of the table 'OrderLine'. The set of foreign keys must be fully contained in the set of primary keys, or fully not contained in the set of primary keys to be mapped to a model.
The relationship 'FK_OrderLine_Product' uses the set of foreign keys '{ProductId, CompanyId}' that are partially contained in the set of primary keys '{OrderLineId, CompanyId}' of the table 'OrderLine'. The set of foreign keys must be fully contained in the set of primary keys, or fully not contained in the set of primary keys to be mapped to a model.
The question is in two parts:
Is my database design incorrect? Should I refrain from these compound primary keys? I'm questioning my sanity regarding the fundamental schema design (frazzled brain syndrome). Please feel free to suggest the 'idealized' schema.
Alternatively, if the database design is correct, then is EF unable to match the keys because it perceives these foreign keys as a potential mis-configured 1:1 relationships (incorrectly)? In which case, is this an EF bug and how can I work around it?
On a quick scan of EF's error messages, it clearly doesn't like the way you're setting up compound keys, and I think it's probably nudging you in the right direction. Give some thought again to what makes your primary keys unique. Is the OrderID alone not unique, without a CompanyID? Is a ProductID not unique, without a CompanyID? An OrderLine certainly should be unique without a CompanyID, since an OrderLine should be associated only with a single Order.
If you truly need the CompanyID for all of these, which probably means that the company in question is supplying you with ProductID and OrderID, then you might want to go a different direction, and generate your own primary keys that are not intrinsic to the data. Simply set up an auto-increment column for your primary key, and let these be the internal OrderID, OrderLineID, ProductID, CompanyID, etc. At that point, the OrderLine won't need the customer's OrderID or CompanyID; the foreign key reference to the Order would be its starting point. (And the CustomerID should never be an attribute of an order line; it's an attribute of the order, not the order line.)
Compound keys are just messy. Try designing the model without them, and see if it simplifies things.
I think that the error is not in the design.
Is not in the EF.
Is in Sql Server relations.
Read the EF message:
The relationship 'FK_Order_Customer'
uses the set of foreign keys
'{CustomerId, CompanyId}' that are
partially contained in the set of
primary keys '{OrderId, CompanyId}' of
the table 'Order'. The set of foreign
keys must be fully contained in the
set of primary keys, or fully not
contained in the set of primary keys
to be mapped to a model.
ERROR
Actualy the relation betwen Order and Customer use only one field (probably you dragged with the mouse the field "CustomerId" from teh Order table to the "Id" of the Customer table)
SOLUTION
Right click on the wire that connect Order and Customer and in the relation add also the CompanyId
PS: The design is correct.
Putting the CompanyId in each table is rith solution in multi-tenant architecture because help to scale (usualy always want to select only records from the loggedIn company).
I think storing the company number in each of the tables is hurting you more than helping. I can understand why you want to do this (as the programmer/dba you can just go into any table and 'see' what data belongs to who which is comforting), but it is getting in the way of you setting up the database the way it should be.
Avoid the compound keys and your design gets a whole lot simpler.
If you have to absolutely add CompanyID column to each table, add it as a regular column and not a composite Key. Composite key is mostly used when you have to implement many to many relationship.
As someone mentioned also create a Non-clustered Index on CompanyID so joins to the Company table are benefitted.
Thanks!
First: like others said, when referencing a foreign key, use the whole primary key in the other table (ie. both fields).
Second, I cannot imagine not using a CompanyID column in most tables in a serious application. Orderdetail might perhaps be an exception in this case (also global lookup tables perhaps, unless they are tenant dependant). Thing is, you cannot do any safe sort of free form search on a table without either adding the CompanyID, or doing JOINs up until the point you reach a table which has that column. The latter one obviously costs performance. Perhaps in this case you could make an exception for orderdetail and only search in the joined version (only two tables). Then again, its not really consistent.
Also regarding making a it a compound key or not: its possible, but opens up the possibility that a bug writes information incorrectly (into non existent, or other people's administrations) for the duration of the bug. Try to fix that in production, not to mention explain it to customers why there are seeing their competitors orders in their system.

Entity Framework Association with Non Key fields

Is it possible to create associates b/t 2 non-key fields in the Entity Framework?
Example: Take the 2 tables in a legacy application (i.e. keys/structure cannot change)
Order (
OrderId : int : PK
OrderNo : varchar
)
OrderDetails (
DetailRecordId : int : PK
OrderNo : varchar
)
In the Entity Framework, I want to create an association b/t Order and OrderDetails by the OrderNo field, which is not a primary key on either table or a FK relationship in the database.
This seems to me as not only should it be easy to do, but one reasons to use something like EF. However, it seems to only want to allow me to create associations using entity keys.
The Entity Framework allows you to claim that columns are keys and that FK constraints exist where none actually exist in the database.
That is because the SSDL (StorageModel part of the EDMX) can if necessary be manipulated by you and lie about the database.
The EF will then interact with the database as if the keys and foreign keys really do exist.
This should work, but all the normal caveats about referential integrity apply.
See my Entity Framework Tips
Hope this helps.
The problem with using non-key fields to define relationships is that the keys are not guaranteed to be properly navigatable. That could lead to a situation where you have a one to one relationship between two entities where there are more than one possible rows that fufill the relationship.
...when relating data from a database, the relationships should always be based on keys. The keys enforce the referential integrity.
One more workaround:
create view vOrder which will not include PK and create Entity from it.
Set PK in this entity to OrderNo
Now you will be able create association