Entity Framework Self Join & Child Objects - entity-framework-4

Using Entity Framework in .net 4.0, how do you set up an entity for the object below?
I have an item that people can comment on and then people can comment on comments and so on
Ex:
Item
-Comment
--Comment
--Comment
---Comment
-Comment
-Comment
--Comment
My current table structure in sql:
Comments
ID (int)
ParentCommentID (int)
ProductID (string)
Title
Text
Thanks

A good idea would be to check out the Stack Overflow Creative Commons Data Dump.
They have a similar setup for post/comments, so you can see how they setup their schema. Hanselman also has a blog post on a OData service for it here, so you can check out his EDMX.
Your on the right track though:
Item 1..* Comments
Comment 1..* Comments
You'll need to setup ParentCommentID as self-referencing FK, then when you import that into your EDMX Entity Framework should model it correctly. You might need to rename the nabigational property to something more meaninful.
Good luck!

Related

Can EF6 use an existing table with GUIDs as the join/bridge table?

I have an existing database and one of the tables for the existing webforms application is a join or bridge table called PostCategory that links up Posts and Categories but it uses GUIDs to do that. It has GUIDs for CategoryID and PostID. When I tried use fluent mapping to point EF at that table I got the error that only ints can be used.
So I suspect the answer is no but I wanted to ask in case someone has done it. According to this post, it is possible with NHibernate but not EF.
This is not possible with EF because it doesn't support unique keys. Only primary keys can be used as principal in relation.
Now the post is from 2012 so I though maybe something has changed with EF6.

Reference data from views in breeze

We have a table (AttendanceType) in our database which have many fields with multiple options. this multiple options are defined in single table. So, instead of creating separate Option table for each option we have single table (Option_Data) with key to identify each option type (Record).
Example : AttendanceType table has following fields
ID
Description
Category (Payroll / Accrual)
Type (Hours / Days)
Mode (Work hours / Overtime / ExtraHours)
Operation (Add / Minus)
These fields have options (data as shown above in brackets) which comes from Option_data table. We have created separate views from this Option_data table example: vwOption_Attendance_Mode, vwOption_Attendance_Operation etc.
Now, how we can link this view in breeze so the reference data come automatically.
We are using EF6, SqlServer, Asp.Net WebApi. When the table relationship is defined in SQL Server Breeze works perfectly and manages the relational data. In this case we cannot define relationship in SQL Server between Table and Views.
How we can code it so Breeze can manage the relational / reference data for us? If you require further clarification please let me know.
Edit # Jay Traband : Let say a single table (ie: AttendanceType) has fields which get reference/lookup data for its field from Views. How in breeze we can relate them (table with views), as in SQL Server we cannot.
My reference points is when Tables are related breeze does excellent job. I want to achieve same with table and views.
Breeze gets its metadata (including the relationships between entities) from EF. You'll need to tell EF about the relationship between the tables and views, even if there is no such relationship defined in SQL Server. This SO post provides some clues, and this blog post gives some related information about creating relationships in the designer.

Change Table Mapping at runtime

I'm using Entity Framework (.net)
We have various departments and One table with different table names has same schema across all departments. like if Department Name is ABC and DEF the table name is ABC_TimeSeries and DEF_Timeseries respectively.
I have created a one class. Now I would like to change the tables name as user selects the department using drop-down selection box.
In your case that you have suffixes, I think Brandon Haynes solution -Entity Framework Runtime Model Adapter- can help.
But I'm going to use interfaces and dependency injection for my similar problem.

Linq to SQL Entity Splitting

I've recently started playing around with the ASP.NET MVC NerdDinner sample, and as part of that you get to play around with Linq to SQL classes. This looks cool, so I decided to break away (perhaps a tad prematurely!) and try and create my own MVC application, but this time modelling my own simple database with Linq to SQL.
The problem I'm having is this. Consider these tables:
Car
Person
Passengers
The table CarPassengers is a mapping table between Car and Person (it has two columns: CarId, PersonId).
In Linq to SQL, I get a class for every table. But, what I really want is a class for Car that has the property CarPassengers, with each child being a Person, rather than the actual FK's (it's ok for selecting results, but to update Car with new Person objects, I have to first construct them - I can't just add an EntitySet of CarPassengers without first instantiating the child Person objects, I think).
I've been looking around and I've seen that the ADO.NET Entity Framework will allow me to achieve this using Entity Splitting, but I wondered if there's an easy way to accomplish the same thing in Linq to SQL, and if not, what the affects are in terms of integrating the .NET EF with my MVC app.
Any advice, comments, tips would be much appreciated.
Thank you!
If you define the FKs prior to adding them to the designer surface you will get the EntitySets added to the class in a manner close to what you expect. CarPassengers will exist but it will be an EntitySet of CarPassenger objects, not Persons. Those objects, however, will have an associated Person EntityRef. This will allow you to find the passengers in the car.
var car = db.Car.Where( c => c.CarId == id );
var passengers = db.Car.CarPassengers.Select( cp => cp.Person );
Adding new passengers works as well, but also involves another step.
var car = db.Car.Where( c => c.CarId == id );
var person = new Person { ... };
car.CarPassengers.Add( new CarPassenger { Person = person } );
If you don't have the FK relationships defined ahead of time, you can always add the associations manually in the designer. MSDN has a HowTo article on this topic.

How to get the foreign key in Entity Framework?

I am developing StudentApp in .NET 3.5 SP1 MVC Application.
I have two tables
Course
CourseID, course_Name
Students
studentID, student_Name, courseID(fk)
Now I made StudentApp.dbml which is having both table as entities.
As Foreign key will not be present in student entity,
I can not display courseID in student model, more over i can not generate add, edit, list views.
So tell me how to display courseID(fk) in student & i also want course name instead.
And also dropdownbox showing course name & storing courseID in edit view .
I'm pretty sure you have to load the foreign reference for each entity. Since I have no idea how you've constructed your API, I'll have to give you a pseudocode'ish example, but I think this is what you need to do.
List<Students> studList = [your_db_facade].SelectStudents() // Or however you retrieve your students
foreach (Students singleStudent in studList)
singleStudent.Context.CourseReference.Load() //CourseReference.Load() should be in the framework
Then you get the CourseID and name from the single student entity like
singleStudent.Course.CourseID
singleStudent.Course.course_Name
It could look slightly different for you, but I think the key to solving your problem is CourseReference.Load().
If your using LINQ-to-SQL and created a DBML file in Visual Studio then the foreign keys can be listed through the Course property in the Student object (automatically generated so since it is a one-to-many relationship from Student). Sort of like this:
var studentCourseIds =
from s in context.Students
select s.Course.CourseID;
Since your goal is to find the coursename then it is already accessible with Student.Course.course_Name.
Can you post your DBML? Also, DBML is used in LINQ to SQL (L2S) - EDMX is the mapping used in the ADO Entity Framework. Are you using LINQ to SQL or the Entity Framework (EF)?
No matter which one you are using - they both support Foreign Keys and you would get a property representing either side of the relationship - you don't need to do anything special (the Foreign Key must exist in the database, of course).
In EF, the foreign keys are called "navigtion properties" and they work a little differently to Foreign Keys in L2S. Nothing major, but updating them and "eager loading" are somewhat different.
Just drop the tables onto the map in the designer in Visual Studio (or generate using command line equivalents if you prefer).
Regarding Foreign Keys and Drop Down Lists (and other UI goodness) - I wrote a couple of blog entries on some approaches which might suit you. One part is located here and part two is located here.
if you create the correct relationship in your SQL server database, then when you add the tables to your DBML designer, the relationships will be copied across also and your code will link up automatically.

Resources