Cannot get the Entity Framework to handle a GUID relationship - entity-framework

I am trying to achieve the following end result. My Person entity needs a collection of extra values and this collection of values will vary from Person instance to instance. I also have another Contact entity that likewise can have extra values form instance to instance.
Therefore I need three tables, a Person, Contact and an Extra where the Extra has the set of extra values for each Person and Contact instance that needs extra values. By giving the Person and Contact a GUID field it means that the GUID values will be unique across both tables and so I can use that as the field to join on. So I expect the definition to look like this...
Person
Id - int - Primary Key
Instance - GUID - Unique Constraint
Contact
Id - int - Primary Key
Instance - GUID - Unique Constraint
Extra
Id - int - Primary Key
Instance - GUID
Value - string
But I cannot model this into Entity Framework. I would like my Person and Contact entities to have a collection each that is the set of Extra values that are relevant to that entity. I create the three tables with the set of columns as indicated above.
But I cannot get the association to work as expected, it always wants to add extra columns to the database based on the primary key of the Person and Contact entities. Any ideas how to actually get this to work? Or maybe this is not possible in EF?

This is not possible with EF because it doesn't support unique keys. Only primary keys can be used as principal in relation.

As answered already, EF does not support unique keys. However, if you don't actually need to do anything with the Id property, it may suffice to tell EF that Instance is the primary key. EF doesn't really care whether it's the primary key at the database level, it merely needs to know whether it can use it as a key itself.
Edit: actually, that still wouldn't work. Besides not supporting unique keys, your Extra.Instance does not correspond to any fixed entity. In order to get it working, you would need to split the Extra table into PersonExtra and ContactExtra tables. That's probably a good idea regardless, as it allows you to add the foreign key constraints at the database level that correspond to those you wish to see in EF.

The EF way of doing this is to use a linking table - a simple table that has two columns, which will be not be visible in your model directly but the collections will be.
e.g.
Person
Id - int - Primary Key
Instance - GUID - Unique Constraint
Contact
Id - int - Primary Key
Instance - GUID - Unique Constraint
Extra
Id - int - Primary Key
Instance - GUID
Value - string
PersonExtra
PersonId - int
ExtraId - int
ContactExtra
ContactId - int
ExtraId - int
or change your Primary Key to be the GUID if your model will permit this.

Related

How to get foreign key value from not fetched relationship?

Having two entities defining relationship by #ManyToOne and #OneToMany, how can I get foreign key without asking from related object and just by looking at defining tables? How do I get OWNER_ID from Owned by something like owned.getOwnerId() instead of owned.getOwner().getId() and still be able to owned.getOwner()?
Map the field in your entity as a basic mapping allows you to use the foreign key directly. You can keep the object reference mapping as well, but one of the two mappings must then be marked as insertable=false, updatable=false so that JPA knows which mapping controls the field in the event they show different values.

How can Code First be used to map surrogate keys

I have legacy tables with Primary keys. These tables also have surrogate keys that have been used to relate one table to another. I would like to map the Membership.User table (uses a Guid PK) but has a property UserName which holds the surrogate key which relates it to the DepoMembers table. DepoMembers has a numeric PK - but has a surrogate key UserName. UserNames are guaranteed to be unique.
In Linq2SQL - to relate these tables in the designer - we add an association where User.UserName is linked to DepoMembers.UserName - and set the multiplicity of the Association to 1:1. then Modify the Navigation Names to singular.
If we take DepoMembers as the Principal End of the relationship - it should follow that If Membership.User does not exist (As in the case - where a user does not manage the application site but exist in DepoMembers) the Navigation Property User will be Null.
How can this be done in Code First ...
The only alternative I've come up with so far is to create a property DepoMembers.User which uses the UserName Property to retrieve the User using the datacontext.
Ren

Entity Framework Code first mapping without foreign key

I have two tables:
Requirement
ID (int) PK
ClientID (int)
JobNumber (int)
Comment
ID (int) PK
Job_ID (int)
Comment (varchar)
The tables don't have foreign keys and there's no possibility of adding any. I'm trying to map them in EF. I have classes for each and I'm trying to define the relationship in fluent code to map the Comment.Job_ID to the Requirement.JobNumber. A requirement can have many comments. Requirement has a list of Comments and Comment has a Requirement property.
I have this mapping setup:
modelBuilder.Entity<Comment>().HasRequired(c => c.Requirement)
.WithMany(s => s.Comments)
.HasForeignKey(f => f.Job_ID);
I'm stuck trying to get Comment.Job_ID to map to Requirement.JobNumber.
Any help appreciated.
It's not possible. With Entity Framework the entity that the Comment.Requirement navigation property is refering to is generally identified by the (primary) key property in Requirement, i.e. by ID. There is no mapping option to define that the target property is anything else than the key property - like JobNumber or another non-key property.
I could only imagine that you could "fake" the primary key property in the model to be JobNumber instead of ID (given that JobNumber is unique in the Requirement table):
modelBuilder.Entity<Requirement>().HasKey(r => r.JobNumber);
I don't know if that could have other unwished side effects. (For sure it doesn't work if JobNumber is not unique because EF wouldn't allow to have more than one entity with the same key attached to a context and updates/deletes and so on wouldn't find the correct record in the database.) It feels wrong and hacky to me. I honestly wouldn't even try that, live with the fact that you don't have a real foreign key relationship in the database, forget the navigation properties Requirement.Comments and Comment.Requirement and use manual joins in LINQ to relate the table data/entities as I need them in a given situation.

Entity framework code first - association on "polymorphic" columns

I have 3 tables:
1. Invoice
InvoiceID int PRIMARY KEY
2. Order
OrderID int PRIMARY KEY
3. Transaction
TransactionID int PRIMARY KEY
Source int
Category string
On table "Transaction", Source (unfortunately) is behaving as a "polymorphic"(??) foreign key (there must be an actual term for that - sorry for my ignorance) that depending on the Category column it'll contain the ID of Invoice or Order.
However there's no actual foreign key.
Using EF 4.1 code first, anyone has any idea how I would create the proper associations?
Help is appreciated!
Thanks
Solution
Uh... Embarrassment is kicking in... I can just map it same way regardless of any actual DB foreign key.
I was having problems while trying to do that but basically wasn't related to this. I had computation properties that I didn't ask the context to ignore which was generating wrong queries.
You probably should create two nullable FKs instead of weak reference like that.
Uh... Embarrassment is kicking in... I can just map it same way regardless of any actual DB foreign key.
I was having problems while trying to do that but basically wasn't related to this. I had computation properties that I didn't ask the context to ignore which was generating wrong queries.

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.