Defining a 1 to many relationship in Entity Framework - c#

I'm trying to create a 1:m relationship using Entity Framework (.net 4.0) and am getting the following error:
App_Code.Model.msl(36,6) : error 3007: Problem in mapping fragments
starting at lines 6, 36:Column(s) [ProductId] are being mapped in
both fragments to different conceptual side properties.
What i have is a Products table, and a Features table. The idea is that Products have many Features. Products each have a ProductId, and the Features have a ProductId foreign key.
Now the catch is that the foreign key doesn't exist in sql server, and i don't want it to. If it did, then it all automagically works nicely.
In the EDMX designer, i created an association from the product to the feature entity, then edited the mapping details of the ProductFeature association to be based on the Features table, which i think would make it work.
Any ideas? Thanks very much.

This is a M x N relationship. Why? Because a feature can be assigned to more than one type of product.
You should have a table ProductFeatures like so:
ProductId FeatureId
1 1
1 2
2 1
2 2

Found one solution: delete the scalar property 'ProductId' from the feature entity:
http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/a71901fb-97ec-4072-949a-c0c66a9775b1
However, in the auto-generated relationships that EF gives you if you set up the foreign key in the database, the eg 'ParentId' fields are present in the child as a scalar field.
So i'm a little confused still.
-edit- Further help:
http://www.hanselman.com/blog/CreatingAnODataAPIForStackOverflowIncludingXMLAndJSONIn30Minutes.aspx

Related

Why SQL server view is not good to work with Entity Framework

i read these articles
http://a4academics.com/interview-questions/52-dot-net-interview-questions/973-entity-framework?showall=&start=2
they said
Below are the points we can consider increasing the performance –
Disable the Change Tracking if it’s not required.
Use the compiled
query whenever required.
Avoid using Views
Fetch the required data
from database.
1) what they try to mean avoid using views.
we can have views in db and that we can refer by edmx. so what would be the problem if we call view by EF instead of table ?
i like to know what happen when we call view by EF.
Thanks
Really the only problem with views is that they don't always contain unique candidate primary keys.
A view can contain rows like
ID1 ID2 SomeColumn
==================
1 4 A
1 5 A
1 5 B
where both ID columns originate from primary key table columns.
When imported into an EDMX, EF will infer a primary key and may conclude that { ID1, ID2 } is a good candidate. As you see, it isn't. In this case it should also include SomeColumn, but in other cases there may not even be a unique combination of view fields!
In Entity Framework 6 and earlier that caused EF to materialize identical entities like
1 4 A
1 5 A
1 5 A (!)
As you see, the third row is duplicated.
This has caused great confusion among developers and lots of Stack Overflow questions. It's just that when the view contains a proper unique candidate key, which is mapped as primary key in the EF model, it's perfectly OK to use views for read-only data in EF queries.
This confusing issue won't be fixed in EF6 any more, but Entity Framework core (as of v2.1) has added support for reading unidentifiable view data. A view can be read into any type and reading the view will simply return the view rows without duplications caused by non-unique keys: there are no keys.
The type can be added to the model by:
modelBuilder.Query<MyViewDto>().ToView("MyView");
...and used in a LINQ query like so:
db.Query<MyViewDto>().Where(x => x.ID1 == 1)
This will be translated into a SQL query with a WHERE clause.

How to have more than 1 many-to-many relationship

My problem is simple but I can't seem to get EF to understand my database schema (Oracle).
Problem
I want to model more than 1 M-M relationship see diagram below:
As you can see I have a book and a journal - and I want to store a URI against both of these, by way of using a linking table (junction table, intersection table, you get it!). In this case it happens to be "www.google.com" that I want to store against Journal 16 and Book 75, they would be stored in the linking table in the follwoing format marked out in blue. For completeness I have added a green example for link with an ID of 5.
So you can see how the data knits together, I think you'll agree it's nothing too crazy.
Anyway, when I try and update EF model, it complains (in Visual Studio) with an error along the lines of.
Problem in mapping fragments starting at line 210:Foreign key constraint 'REF_URI_JOURNAL_FK1' from table REF_URI (REF_ID) to table JOURNALs (REF_ID): The columns of table REF_URI are mapped to AssociationSet BOOK_URISet's End BOOKs but the key columns of table JOURNALs are not mapped to the keys of the EntitySet BOOKs corresponding to this End.
Yeh - not really getting that error message!
I can get EF to work with 1 M-M relationship, e.g.
and it all works "hunky dory", but when I added a second M-M relationship it fell over with that error message above e.g.
Anyone know how I can get round this?
For two many-to-many relationships your need two linking tables (junction tables, intersection tables) REFBOOK_URI and REFJOURNAL_URI. I think that is what the exception is saying in a cryptic fashion. If you only had one table it would mean that if Journal 123 links to URI 789 then also Book 123 must also link to URI 789 because the REF_ID column in the link table would be a non-nullable foreign key to both the Journal and the Book table.

EF4: Using the same table twice

I'm using an Oracle datasource, reading data only, not writing, I can not alter anything on the database.
Imagine this scenario of 2 tables, a Courses Table and a Memos Table.
The Courses table has 2 links to the memo (MemoId) table.
So...
Course table
CourseId
Title
SummaryNarrationMemoId
PreCourseInformationMemo
MemoToString table
MemoId
MemoData (Binary)
So the course table joins to the Memo Table twice, for different reasons.
I looked down the EF Inheritance route for using the same table twice, using the Memo table as the base, and creating PreCourseMemo and SummaryNarrationMemo, but that throws these errors on build:
I updated the model to add the two tables to the model.
Error 3005: Problem in mapping fragments starting at line 613:Must specify mapping for all types in Set MemoToStringTables.
An Entity with Key (PK) will not round-trip when:
Entity is type [MyModel.MemoToStringTable]
Error 3005: Problem in mapping fragments starting at line 613:Must specify mapping for all types in Set MemoToStringTables.
An Entity with Key (PK) will not round-trip when:
Entity is type [MyModel.PreCourseMemo]
Error 3005: Problem in mapping fragments starting at line 613:Must specify mapping for all types in Set MemoToStringTables.
An Entity with Key (PK) will not round-trip when:
Entity is type [MyModel.SummaryNarrationMemo]
I know I could create a view for each on the database, but it doesn't feel right. :( Any thoughts?
If I understand your problem correctly, it will not work. You are trying to map inheritance to the Memo table but to do that you Memo table must contain special discriminator column which will tell EF if it is PreCourseMemo or SummaryNarrationMemo. You cannot differ those types just by relation to course.

Table-per-type inheritance insert problem

I followed this article on making a table-per-type inheritance model for my entities, but I ran into some issues. Below I'm posting steps to reproduce the problem I'm having in a minimal environment to rule out other factors.
First, I created a new MS SQL Server 2008 R2 database with the following two tables:
Users
Id : bigint (PK and set it as the identity column)
Name : nvarchar(25) NOT NULL (whatever, some random property
Customers
Id : bigint (PK, identity column, and FK on Users.Id)
Title : nvarchar(25) NOT NULL (also whatever, some random property)
Next, I generated the .edmx entity model from the database, and followed the link at the top verbatim. That is to say, I deleted the association between User and Customer, set User as the base class of Customer, deleted the Id property from the Customer entity, and made sure that the Customer.Id column was mapped to the inherited User.Id property. I then ran the following small program:
using (var db = new EF_Test.testEntities())
{
var cust = db.Users.CreateObject<Customer>();
db.Users.AddObject(cust);
db.SaveChanges();
}
I get the following error when I make that last call:
"A value shared across entities or associations is generated in more than one location. Check that mapping does not split an EntityKey to multiple store-generated columns."
With the following inner exception:
"An item with the same key has already been added."
Any ideas on what I could be missing?
A quick google on the error message turned up the following solution, maybe it helps you:
http://social.msdn.microsoft.com/Forums/en/adodotnetentityframework/thread/4bfee3fd-4124-4c1d-811d-1a5419f495d4
I think that I figured it out. The
table for the Party sub type had its
key column set to autogenerate a key
value and since it's derived, the EF
wanted to set that value explicitly.
So have you tried removing the "identity" setting from the customer table? So it doesn't autogenerate the primary key?
Hope this helps.
I finally found the source of my troubles. For those still interested, in the Customers table, the Id column should not have been set to the identity column of the table (PK and the FK dependency are fine though).
Why you don't want to make a foreign key (UserId) as a separate column? Maybe it can help you.
Also try to use model first approach and generate db after model creation as it is described in the following article.

MVC Entity Model not showing my table

I have a database with multiple tables, and some basic relationships. Here is an example of the problem I am having:
My Database:
**Org**
ID
Name
etc
**Detail1**
ID
D1name
**Org_Detail1**
Org_ID
Detail1_ID
**Detail2**
ID
D2Name
**Org_Detail2**
Org_ID
Detial1_ID
BooleanField
My problem is, the Org_detail1 table is not showing up in the entity model, but the Org_Details2 table does.
I thought it may have been because the Org_Detail1 table only contains two ID fields that are both primary keys, while the Org_Details2 table contains 2 primary key ID fields as well as a boolean field.
If I add a dummy field to Org_detail1 and update it, it still won't show up and wont allow me to add a new entity relating to the Org_Detail1 table. The table won't even show up in the list, but it is listed under the tables.
Is there any solution to get this table to appear in my model?
Seems like I may just need to completely delete the model and recreate it. Adding dummy fields is the only solution I've found.
Not sure this is an MVC problem.
Does a Detail1 collection turn up in your Org entity and an Org collection show up in your Detail1 entity. This is the normal behaviour for Entity framework for a many to many intersecting table with no other tangible data.
If not then maybe the foreign key constraints are not defined.

Categories