Entity Framework - ObjectContext.DeleteObject() when related entities are orphaned - entity-framework

I have two entities in a many to one relationship. Widget (1) <--> (*) Users.
If for some strange reason there has been a Widget deleted in the database, where there may not be a foreign key or other referential constraint that would prevent a Users from existing if there was not a corresponding Widget, I cannot use EF to ObjectContext.DeleteObject(). The message is
System.Data.UpdateException: Entities in '<Users>' participate in the '<UsersWidgets>' relationship. 0 related 'Widgets' were found. 1 'Widget' is expected.
at System.Data.Mapping.Update.Internal.UpdateTranslator.RelationshipConstraintValidator.ValidateConstraints()
Is there a recommended way to deal with this in code?
Thanks!

You should modify your Entity Data Model (EDM) to conform to the rules expressed in the database schema.
If there aren't any referencial integrity constraints between the User and Widgets tables in the database and the foreign key column in User is nullable, then the association between their corresponding entities in the EDM should have a multiplicity of 0..1:* (zero or one-to-many).
Right now it is probably set to 1:* (one-to-many) which is causing the validation error, since according to that a User is always expected to have exactly one associated Widget.
Related resources:
Association End Multiplicity (Entity Data Model)

This Exception usually occurs, if you have an FK on Users to Widgets, which is NOT nullable in the DB. So the first thing you should check is, if the FK is defined as nullable on Users.
Which Database do you use? I am only aware with MSSQL Server 2008. If so check which properties are set on the relation in the database. You can define an UPDATE and DELETE action on a relation. If you dont want the user to be deleted when the Widget is deleted you should check if cascade delete is disabled. There is also an option to set the Widget on the User to null.

Related

Why can't I have a referential constraint with a one to zero-to-one association?

I'm using entity framework 4.3 model first and can't figure out why I'm not allowed to have a one to zero-to-one association along with a referential constraint.
I have two main problems. I can't force referential integrity (without manual intervention) and my lazy loading doesn't seem to work... all my 1 to many associations are fine.
I basically have two tables, Loans and Contracts. The Contracts table has a scalar field for LoanId.
Until a loan is submitted, it does not have contract data and I chose not to place everything in the same table due to the size of the contract data. Ie. I don't want contract data retrieved from the database unless it is actually required.
I've searched around and can't seem to find any model first information that clearly answers my questions. Any information that may help me understand and clarify my problem would be greatly appreciated.
Regards
Craig
I guess LoanId field is not a primary key in Contracts table. In such case you cannot have such one-to-one relation because EF doesn't support it. When you create LoanId field in Contracts table the only way to force one-to-one relation is to add unique constraint on that field. EF currently doesn't support unique keys (except primary keys) so the only way to create one-to-one relation is to create relation between primary keys (Loan.Id <-> Contract.Id). If you don't follow this you will get error in designer.

ADO.NET Entities not picking up an FK relationship

I've got a table "Persons" (PersonId, Name, Address) which contains information about people. I then subclass this information with tables "Clients" (PersonId, DateJoined) and Victims (PersonId, DateAssassinated).
In SSMS I have established an FK relationship FK_Clients_Persons and FK_Victims_Persons where the Primary Key is Persons.PersonId and the foreign key is the eponymous field in the Clients and Victims tables respectively. In SSMS I cannot see any obvious functional difference between these relationships.
However, in ADO.NET Entities when I create the model from the database, the tool does not identify FK_Victims_Persons but it does recognise FK_Clients_Persons. It just treats Victims.PersonId as a simple field and doesn't generate relationship members for it. The missing FK relationship does not appear in the Constraints tree of the Model Browser, but the other one does.
I have no idea why this is, has anyone faced this problem before?
No matter how many times I start over, I can't get it to work.

Linq Mapping Problem with 1 to 0.1 relationships

I have an linq to entity mapping issue. I have three tables.
Table 1 - ItemsB(ID(key), Part_Number(will be null until built), other item b information)
Table 2 - ItemsA(ID(key), Part_Number(will be null until built), other item a information)
Table 3 - WebItems(Item_id, web item information) *Consists of items from both ItemsB and ItemsA after they are built and pushed over to this table.
ItemsA/ItemsB will have a 1 to 0.1 relationship with WebItems. Part_Number maps to Item_id.
I am using EF4.0.
Problem is after i set up the association/mappings as stated above i get an error message stating: "Problem in mapping fragment at lines so and so: Column [Part_Number] are being mapped in both fragments to different conceptual side properties."
Usually i know what to do in this case. Get rid of the property [Part_Number]. Problem is i need to access [Part_Number] in both ItemsB and ItemsA quite frequently without going to webitems. Not to mention webitems will not always have the [Part_Number] populated at certain points depending upon whether the items have be pushed to webitems.
Does anyone know how to get around this?
Thanks in advance.
As I understand it ItemA and ItemB to WebItem in one-to-one relation. One-to-one relation in EF always demands that relation is build on primary keys and one side is mandatory (principal) because dependent entity will have primary key and foreign key in one column. Once you assign primary key in dependent entity you must have principal entity with the same primary key otherwise you will violate referential integrity defined by foreign key.
The problem is that your Part_Number is primary key and foreign key in the same time. To allow such mapping in EFv4 you must use Foreign Key association instead of Independent association. Here is brief description how to create foreign key association in the designer. Once you define referential constrain get back to mapping window of association and delete the mapping.

Trouble inheriting from another entity

I'm having trouble configuring entity relationships when one entity inherits from another. I'm new to ADO Entity Framework -- perhaps someone more experienced has some tips for how this is best done. I'm using .net 4.
Database tables with fields:
Products (int ID, nvarchar Description)
FoodProducts (int ProductID, bit IsHuge)
Flavors (int ID, int FoodProductID, nvarchar Description)
There are constraints between Products and FoodProducts as well as FoodProducts and Flavors.
Using the designer I create a model from the database. The designer seems to get it right, with a 1:0..1 association between Product and FoodProduct entities, and 1:* association between Flavor and FoodProduct. No errors when I save or build.
Next I set FoodProduct entity to inherit from Product entity. Then I get errors concerning relationship between Product and FoodProduct. Ok, starting fresh, I first delete the relationship between Product and FoodProduct before setting the inheritance. But now I get errors about the relationship between FoodProduct and Flavor. So I delete and then recreate that relationship, connecting Flavor.ID to FoodProduct.ProductID. Now I get other errors.
My question is this: Should I instead be creating relationship between Flavor.FoodProductID and Product.ID? If so, I assume I then could (or should) delete the FoodProduct.ProductID property. Since my database will have many of these types of relationships, am I better off first creating the entity model and exporting the tables to SQL, or importing the database schema and then making many tweaks?
My intent is that there will be several types of products, some of which require many additional fields, some of which do not. So there may be zero or one FoodProducts records associated with each Product record. At least by my thinking, the table for each sub-type (FoodProducts) should be able to "borrow" the primary key from Products (as a FK) to uniquely identify each of its records.
You can find a screen capture here: http://img218.imageshack.us/img218/9720/entityframework.jpg (I'd embed the img but haven't earned the requisite rep' yet!)
Well, I deleted the FoodProduct.ProductID field, as it should always return the same value as Product.ID anyway. Then, as you hinted, I had to manually map the Products.ID field to FoodProducts.ProductID field. Errors resolved. I'll write a little code to test functionality. Thanks for the "observations"!
Couple of observations:
FoodProducts needs a primary key (e,g identity - FoodProductID). Are you sure it should be a 1:0..1 between Food and FoodProducts? I would have thought it should be 1:0..*. For this cardinality to work you need a unique PK on this table.
When you setup inheritance for entities, the parent entity's properties are inherited. So FoodProducts will inherit ID from the Product table.
BUT, on the physical model (database), this field still needs to be mapped to a column on the FoodProducts table - which is why you need the identity field.
After you setup inheritance, you still need to map all the columns on the derived tables. My money is on you have not mapped "ID" on FoodProducts to any column.
If you screencapped your model and show the errors you are getting it would be much easier to diagnose the issue.

Entity Framework - Change Relationship Multiplicity

I have a table [User] and another table [Salesperson] in my database. [Salesperson] defines a unique UserID which maps to [User].UserID with a foreign key. When I generate the model with Entity Framework I get a 1-to-Many relationship between [User]-[Salesperson], meaning that each User has a "Collection of Salesperson", but what I want is a 0..1-to-1 relationship where each User has a nullable reference to a "Salesperson".
I tried fiddling around with the XML and changing the association's multiplicity settings, but that only produced build errors. What I am trying to achieve is no different than having a nullable SalespersonID in [User] that references [Salesperson].SalespersonID, but because salespeople only exist for specific users it feels like I'd be muddying up my [User] table structure just to get the relationship to point the right way in Entity Framework.
Is there anything I can do to change the multiplicity of the relationship?
Make the PK of Salesperson itself a FK to User. The EF's GUI designer will then get the cardinality correct, since PKs are unique.