Entity framework code first - association on "polymorphic" columns - entity-framework

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.

Related

EF query contains incorrect elements

I have a query with EF which looks like this:
var x = _db.qMetaDataLookups.ToList();
if I execute, direct on the SQL server SELECT * FROM qMetaDataLookup, 2155 distinct rows are returned. After executing the above, x ALSO contains 2155 elements.
The problem is that the data is wrong. I'm not getting the same data back from the EF as I do from the SQL Query.
In particular, theres a particular element that exists on the SQL output, call it "WXYZ", which makes no appearance at all in the EF version of the query (against the exact same database).
Instead, what I find are numerous repeats. If I call x.Distinct() the list filters down from 2155 elements, to a mere 143.
I'm flummoxed. I have never seen my EF and SQL results differ on a query this simple. There must be a very simple [face-palm] explanation, but I'm missing it.
Thanks.
EDIT qMetaDataLookup (a view) are contains information about our database. In essence, its a listing of all tables and views, and each of their columns, with other information about the datatype, length, precision, scale, etc. The 'key' in this table ought to be the column that matches "tableName.columnName" but instead EF chose for it all the datatype properties. This is why the query fails to perform as desired.
Make sure the entity key is set correctly for qMetaDataLookup in the Entity Data Model. Sometimes the entity keys are messed up...
The issue might have been that your model was using a key with duplicate values where the Entity Framework was expecting unique values. This would happen if, for example, your data model used a composite primary key composed of foreign keys from other tables. It seems EF doesn't like composite primary keys very much, and so returned results from queries will generate what appear to be duplicated rows.
The fix seems to be to add a surrogate primary key column to your table which is guaranteed to be unique. If you still need to reference the foreign columns that's fine, so long as they aren't being used as a composite primary key for the table.
I can't claim any credit for the solution, but here's the link that helped me solve my issue:
http://jepsonsblog.blogspot.ca/2011/11/enitity-framework-duplicate-rows-in.html

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.

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.

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

GUID or int entity key with SQL Compact/EF4?

This is a follow-up to an earlier question I posted on EF4 entity keys with SQL Compact. SQL Compact doesn't allow server-generated identity keys, so I am left with creating my own keys as objects are added to the ObjectContext. My first choice would be an integer key, and the previous answer linked to a blog post that shows an extension method that uses the Max operator with a selector expression to find the next available key:
public static TResult NextId<TSource, TResult>(this ObjectSet<TSource> table, Expression<Func<TSource, TResult>> selector)
where TSource : class
{
TResult lastId = table.Any() ? table.Max(selector) : default(TResult);
if (lastId is int)
{
lastId = (TResult)(object)(((int)(object)lastId) + 1);
}
return lastId;
}
Here's my take on the extension method: It will work fine if the ObjectContext that I am working with has an unfiltered entity set. In that case, the ObjectContext will contain all rows from the data table, and I will get an accurate result. But if the entity set is the result of a query filter, the method will return the last entity key in the filtered entity set, which will not necessarily be the last key in the data table. So I think the extension method won't really work.
At this point, the obvious solution seems to be to simply use a GUID as the entity key. That way, I only need to call Guid.NewGuid() method to set the ID property before I add a new entity to my ObjectContext.
Here is my question: Is there a simple way of getting the last primary key in the data store from EF4 (without having to create a second ObjectContext for that purpose)? Any other reason not to take the easy way out and simply use a GUID? Thanks for your help.
I ended up going with a GUID.
The size/performance issues aren't
critical (or even noticeable) with SQL Compact, since
it is a local, single-user system.
It's not like the app will be
managing an airline reservation
system.
And at least at this point, there
seems to be no way around the "no
server-generated keys" limitation of
the SQL Compact/EF4 stack. If someone has a clever hack, I'm still open to it.
That doesn't mean I would take the same approach in SQL Server or SQL Express. I still have a definite preference for integer keys, and SQL Compact's bigger siblings allow them in conjunction with EF4.
Use a Guid. AutoIncrement is not supported on Compact Framework with Entity Framework.
Also, if you ever want to create a application which uses multiple data sources, int PK's are going to fall apart on you very, very quickly.
With Guid's, you can juse call Guid.NewGuid() to get a new key.
With int's, you have to hit the database to get a valid key.
If you store data in multiple databases, int PK's will cause conflicts.
What I've done for SQL CE before, and I assume we have a single application accessing the database, is to calculate the MAX value on startup and put it in a static variable. You can now hand out sequential values easily and you can make the code to generate them thread safe very easily.
One reason to avoid Guids would be size = memory and storage space consumption.
You could also query SQL Compact metadata like so:
SELECT AUTOINC_NEXT FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Categories' AND AUTOINC_NEXT IS NOT NULL