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

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.

Related

EF Nullable Foreign Key Relationship

I need some help today related to EF relationship. I have two lookup tables Country and Ethnicity. I want to have nullable foreign keys for both in one my table named Singles, so I defined a relationship in my class like
Single Relation
that generate a table like this, which is good so far
Single Relation Result
But I have other fields like Citizenship and CountryOfBirth which require a foreign key as well from Country table. So, I tried to do the same
Multiple Relation with Same Class
But things getting weird inside sql when table created.
Multiple Relation with Same Class Result
I can understand why it behaves odd but don't know how to make it work. Can you please suggest?
Thanks
You'll need to place your ForeignKey attributes on the navigational properties to point to the nullable ID field (instead of vice-versa), and then use the InverseProperty attribute to properly tell EF exactly what kind of relationship you are trying to accomplish.
This answer will be quite similar to that in this SO question.

How to decide a Primary Key from an Entity Collection programmatically

I'm encountering some problems importing my DB on Entity Framework. Some relationship between tables returns me some other entities without any primary key.. For my application I need to have a PK for every table.
Is there any way to say something like:
MyEntityCollection.SetKey("ColumnName")
Or something like that?
Thank you very much!
Take a look here, i discuss this in this answer,
EF4 Unknown Column In Field List
http://xhalent.wordpress.com/2011/01/21/configuring-entity-framework-4-codefirst/ has some detail around the two ways in EF4 of specifying a FK

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.

Why does DBIx::Class not create many-to-many accessors?

While creating a schema from a database many-to-many relationships between tables are not created.
Is this a principal problem?
Is it possible to detect from the table structure that many-to-many relationships exist and create the respective code in schema classes automagically?
It is indeed a somewhat fundamental problem -- many_to_many is a "relationship bridge" and not a "relation." The documentation explains that "the difference between a bridge and a relationship is, that the bridge cannot be used to join tables in a search, instead its component relationships must be used."
On the other hand, this means that if the real relationships are correctly discovered it should be straightforward to add the many-to-many relationships automatically: First, search for tables that have two or more has_many relationships. Then, for each pair of such relationships, create a many-to-many relationship bridge. (Of course, one might hope that DBIx::Class would do this itself.)
The problem with developing this kind of code is that many tables that contain multiple references are not many-to-many tables, and have multiple references for other reasons. For instance, I'll make up a schema for some fictional app where something could be regarded as a many-to-many table, when it is not.
create table category (
id primary key,
...
);
create table sub_category (
id primary key,
category references category(id),
...
);
/* EDIT:
This is the table that could be regarded as many_to_many
by an automated system */
create table product (
id primary key,
category references category(id),
sub_category references sub_category(id),
...
);
Something could be built this way for ease of use, without having to do multiple table joins in the database on a website, especially when considering speed. It would be difficult for a piece of code to say definitively 'this is not a many_to_many' situation, while the developer should be able to easily figure it out, and add in the many_to_many line below the checksum.
I consider DBIX::Class schema outputs a good starting point, and little more, especially when working with auto numbering in non-MySQL databases, among other things. I often need to modify above the "Don't modify above this line" stuff (although many_to_many can obviously go below that checksum, of course.

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.