I'm trying to use EF to model an existing SQL database. The DB is multi-tenant by having a clientID column in every single table (I cannot change this). I have table structure like the following.
Table 'ItemID' columns:
ClientID (pk)
ItemID (pk)
ItemName
Table 'Items' columns:
ClientID (PK)
ItemID (PK) [FK to ItemID.ItemID]
Version (PK)
ItemAttribute1
ItemAttribute2
ItemAttribute3
The DB is designed to store previous versions (rows) of the 'Item' object, hence the 'Version' column and PK.
I am new to the EF and trying to adopt it for my project. However, it seems that EF cannot handle this situation very well. I am open to all ideas including using stored procedures or views instead of access tables directly from EF. What about getting rid of the PKs and using 'independant' relations instead?
One specific problem I ran into is that EF (at least the designer) requires all PKs in one table be mapped to all PK columns in any related table. This does not make sense to me, as the example I've given will never work given that constraint. I am trying to make Items inherit from ItemID. The error I get is:
Error 3003: Problem in mapping
fragments starting at line 170:All the
key properties (ItemID.ClientID,
ItemID.ItemID) of the EntitySet ItemID
must be mapped to all the key
properties (Items.ClientID,
Items.ItemID, Items.Version) of table
Items.
I have been looking up all I can find on this topic and nothing has answered these questions for me. I appreciate any help. Thanks.
The error that you are getting from your EDM is coming from the fact that EF supports inheritance only if both entities have the exact same primary keys (hence a one to one relationship on database) so you cannot have inheritance between these 2 entities according to the current schema.
However, I don't see a problem on having a One to Many association between ItemID and Items entities and I believe this is the default EF behavior when you update your model from the database.
Please have a look at this post for more info:
Entity Framework, TPT Inheritance
Related
We are migrating a Microsoft Access application that has an SQL Server Back End to VB.NET for the frontend, and using LINQ to SQL. Most of the tables do not have a foreign key relationship on the database level, and the relationships are handled in code. Most of this works fine, but I am having trouble with times when the value to go into the foreign key doesn't actually exist.
In the small sample data set I created below to illustrate my problem, the Orders table is related to the Suppliers table through the SupplierID field in the Orders Table. I created a OneToMany association with the Suppliers as the Parent, and the Orders as the Child. This gives me a Supplier.Orders list, and an Order.Supplier property which is GREAT!
In my records the SupplierID in the Orders would be SupplierID from the Suppliers table, but there are a few 'magic values'. In this example 0 = No Supplier Exists, and -1 = TBD.
Any suggestions on how to best handle this?
I've handled this a few ways in the code so far, and none of them seem to be great:
I can manually set the Order.SupplierID property to 0 or -1, but I can only do that if I haven't already touched the Order.Supplier property. If I've already done something that makes LINQ use that association, it throws a foreign key error if I try to set the ID to something that doesn't exist.
I can set the value bypassing the LINQ by making an SQL statement(ie: dc.Connection.CreateCommand) but now I'm no longer working within the LINQ layer
I could make those 'magic IDs' actually exist, but from an architecture standpoint that feels wrong, since 'No Supplier' and 'TBD' are not actually suppliers. I would then also need to adjust anywhere that I show a list of the real Suppliers to not show those items.
I'm having trouble articulating my question well, so I apologize in advance.
This isn't the actual table structure/situation I'm dealing with, but I think it was a simpler way to demonstrate.
I have a database with table Photos and table Categories. Each photo is related to one category by categoryId field.
What happens when I delete one category from Categories table? Will the photos with that category be updated with a null value in the categoryID? Or how will entity-framework react to this change?
Another question can I then reset with a mass-change the values of those categories in the photos table? And how can I do that?
hi if you have created relationship between table(using foreign key) then only the deletion of parent table will affect deletion of child table. if you just created table separately and managing relationship with your code then it will not affect the child table. if you are creating using model first approach in entity framework with specifying relation then relationship will be automatically created in backend.
their are four options available in sql on deletion of parent entity
1)No Action
2)Cascade
3)SET NULL
4)SET Default
to know how it will affect check this article
https://www.mssqltips.com/sqlservertip/2365/sql-server-foreign-key-update-and-delete-rules/
That would depend completely on how the ORM that is used defines the database model.
Assuming you use Entity Framework then you can define exactly how EF should react to that situation. In the DbContext you should find a OnModelCreating method in wich you can specify per table what restrictions you want on the table. There you can also define the behaviour of the OnDelete of a foreign key.
If you are not using EF but have your own or a different ORM then again, it depends on how that ORM is configured.
Simple check if you dont know about the used ORM is this: Does the field in the database have a foreign key and how is that configured? Also, is the field categoryID (as defined in the database) nullable? if so, then it apparently doesnt need the relation and shouldnt result in related deletes.
Maybe i'm going about this wrong but my working on a database design for one of my projects.
I have an entity with a classification column which groups up entities into convenient categories for the user. These classifications are predefined and unchangeable by the user (at least thats the current design).
I'm trying to decide if I should have a 'EntityClassification' table which contains simply an 'Id' column as the primary key with no other information in order to have an enforced relationship between the Entity:Classification -> EntityClassification:Id.
I don't plan to have a name/description column in EntityClassification since my current thought is that I'll need to support localization of these pre-defined names which will be done with static string table like resource files downloaded to the client based on their country/language. There really isn't any other data which is associated with this EntityClassfication that I would want and a table seems like it might be an overkill?
Is this common/recommend practice for this type of problem? We're using SQL Server 2008 and don't have an enum datatype for the database which would seem to be really what i'm trying to achieve.
You should have the table with name and description not only for end user display, but internal documentation so when the users say 'my query based on this classification doesn't work!' someone hired in the future will know which ID they're talking about.
Do you just want to ensure that the values in Entity:Classification are restricted to your pre-determined list? If so a check constraint might be what you need.
Such constraints aren't as flexible as foreign keys: to alter the checked values we have to drop and recreate the constraint, but then you say there are no plans to change the values so that shouldn't matter.
This is not a duplicate of this post although the title is very similar. I am using EF4 with MSSQL Express 2008 R2 on VS2010.
A simplified version of my schema is as follows:
Table [Team]:
Id (PK)
Member1
Member2
Table [Person]:
Id (PK)
FirstName
[Team].Member1 and [Team].Member2 are foreign keys pointing to [Person].Id.
When generating the .edmx via VS2010, the navigation properties under [Team] become "Person" and "Person1" despite giving distinct names to the FKs inside SQLServer.
Is it possible to force the .edmx generator to recognize my FK names in SQL Server? I'd like these names to be Member1Person and Member2Person, for example, so I don't have to manually rename them by hand. If not, what is the preferred way to redesign the tables/FKs to bypass this altogether? Thank you.
I have had a similar issue but I believe the answer to the question is you simply have to rename the Navagation property to what you want. The Entity Framwork designer will always keep you changes to the property names on the Conceptual side of things.
I am building a database as a simple exercise, it could be hosted on any database server, so I am trying to keep things as much standard as possible. Basically what I would like to do is a 'code' table that get referenced by other entities. I explain:
xcode
id code
r role
p property
code
r admin
r staff
p title
....
then I would like to have some view like:
role (select * from code where xcode='r')
r admin
r staff
property (select * from code where xcode='p')
p title
then, suppose we have an entity
myentity
id - 1
role - admin (foreign key to role)
title - title (foreign key to property)
Obviously I cannot create foreign key to a view, but this is to tell the idea I have in mind. How can I reflect such behaviour using whenever possible, standard sql syntax, then as a second option, database additional features like trigger ecc... ?
Because if I tell that role and title in myentity are foreign key to 'code', instead of the views, nothing would stop me to insert a role in title field.
I have worked on systems with a single table for all codes and others with one table per code. I definitely prefer the latter approach.
The advantages of a table per code are:
Foreign keys. As you have already spotted it is not possible to enforce compliance to permitted values through foreign keys with a single table. Using check constraints is an alternative approach but it has a higher maintenance cost.
Performance. Code lookups are not normally a performance bottle neck, but it undoubtedly helps the optimizer to make sensible decisions about execution paths if it knows it is retrieving records from a table with four rows rather than four hundred.
Code groups. Sometimes we want to organise a code into sub-divisions, usually to make it easier to render complex lists of values. If we have a table per code we have more flexibility when it comes to structure.
In addition I notice that you want to be able to deploy "on any database server". In that case avoid triggers. Triggers are usually bad news in most scenarios, but they have product-specific syntax.
What you are trying to do is in most cases an anti pattern and design mistake. Just create the different tables instead of views.
There are some rare cases where this kind of design makes sense. In this kind include the xcode field in the primary key/ foreign key. So your entity will look like this:
myentity
id - 1
role_xcode
role - admin (foreign key to role)
title_xcode
title - title (foreign key to property)
You then can create check constraints to enforce role_xcode='r' and title_xcode='p'
(sorry I don't know if they are standard, they do exist in oracle and are so simple that I'd expect them on other rdbms's as well)