How to get the foreign key in Entity Framework? - asp.net-mvc

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.

Related

Remove entries from a table that maintains a many to many relationship asp.net mvc entity framework

I am writing an application based on an existing database. I have two tables, a server table and a support table (people who support the specified server). These tables can have a many to many relationship, and as such I cannot maintain a foreign key within one of the tables pointing to another.
The solution that the person who designed the schema came up with was to add a third table, a server support junction, that has just two columns - ServerID and SupportID, both foreign keys pointing to their respective table.
When I import this database schema into Entity Framework, it gives me the following warning:
Warning 2 Error 6002: The
table/view 'dbo.Server_Support_Junction' does
not have a primary key defined. The key has been inferred and the definition
was created as a read-only table/view.
As such, the table does not appear in the edmx model and it does not create a class for the table.
As part of the application, I would like the DBA to be able to delete a server or a support (they leave the company/no longer support a certain server/etc). Is entity framework smart enough to see that this table is purely relational and will remove any connections when a support or server is deleted? Or must this be done explicitly?
If it must be done explicitly, what is a workaround for this? I tried adding a primary key called RelationID to the table, but it yelled at me saying that the primary key was not mapped or something.
Gert Arnold helped to find the solution. First, a primary key was added to the table consisting of both the Foreign keys, the SQL was:
ALTER TABLE dbo.Server_Support_Junction
ADD CONSTRAINT pk_ServerSupportJunc PRIMARY KEY (ServerID, SupportID)
I then updated the model by opening the edmx, right clicking on the blank space -> update model from database -> refresh -> finish.
To delete the relationship in the controller, the code was as follows:
Support support = db.Support.Find(id);
support.Servers.Clear();
db.Support.Remove(support);
db.SaveChanges();
Obviously you should do some error checking to make sure the entity was actually found, but that's the gist of it!
Special thanks to Gert Arnold!

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.

code first foreign key to asp membership table

I have a table (say, 'MyTable') created using CF. Also, there's asp's Membership table in my DB, which was auto generated along with Users, UserInRoles and Roles tables. These table exist only in the DB, and not as a model (class) in the project.
Now, I need to set a foreign key in 'MyTable' to Membership table. The problem is, of course, that there is no 'Membership' class in my project so I can't set that FK with code first.
I'd like to keep my users management in the trustful hands of asp.net, so I don't want to create my own tables for this.
How can I set that FK using code first?

EF 4.1 code first with Existing Database.Mapping Fks,table etc.Clarification needed

I am learning code first and I have project to be used with an existing database.
I am a bit confused of what I meant to be doing.I will explain:
Do I need to create an entityconfiguration for each table in my existing database?
Within this EntityConfiguration for each table do I need to create foreign key relationships?
Do I need to do a ToTable for each table in my existing database?
Is there any free tool "codeplex" that pointing to an existing db will generate this codeFirst stuff?
I have seem few blogs about "EF Code first with existing db" but I am not sure or was not clear to me If Need to create this stuff or I will be getting strange errors like "MyColumn_MyColum" basically as if codeFirst is trying to build some FKs or something.
can somebody clarify?
thanks a lot. I know there are few questions but if you can answer 01 or 2 that would be fine.
thanks again
If you want the code to be generated for you use database-first approach with DbContext API. Simply create EDMX file from your database and let DbContext Generator template generate all entities and context for you.
DbContext Fluent API is mainly targeted to the code-first development approach where EF will created database for you from the code you provided. It can be used with existing database but it requires much more skills and understanding of mapping wich EF can provide to you.
Generally:
You don't need to provide EntityConfiguration for each table if you follow some naming conventions (entity name is singular form of table name, all properties have the same name, primary key in table and entity is named as Id or EntityNameId, etc.).
You don't need to define relationships manually if you follow conventions with exposing navigation properties and possibly also foreign key properties. The issue can be naming of many-to-many keys and junction tables.
ToTable is needed only if your entity does not follow naming convention or if you map some advance inheritance or splitting.
EF uses a lot of default conventions which drive how the names should be defined. Conventions can be removed.
You will not do anything wrong if you define EntityConfiguration for each table - it will at least allow you learning what is needed and your mapping will be explicit / self documented.

Entity Framework 4.0 2 many-to-many with same entities

I have 2 entities (say People and Books) that have two many-to-many relationships. I have created two different linking tables - e.g. the linking tables are called BooksCheckedOutByPeople and BooksOnHoldByPeople.
EF 4.0 correctly makes two relationships. It calls them something like PeopleBooks and PeopleBooks1.
When I am making Linq queries, how do I tell Linq to use a specific one of these relationships? Is there any way in Linq to specify one relationship instead of the other?
Say I'm creating a query against People and I want to get the Books for BooksCheckedOutByPeople and thus I need to use the relationship PeopleBooks.
Thanks.
You should be able to rename "PeopleBooks" and "PeopleBooks1" to more informative property names by editing the model EF generates for you. Something like "BooksOnHold" and "BooksCheckedOut".
At that point, when writing your LINQ queries, just reference the right navigation properties (as they're called). LINQ uses whichever properties you specify, and the Entity Framework should generate a unique navigation property for each collection.
Edit
I just fired up VS2010 to copy your model and poke around a bit.
I see that EF4 did indeed generate two Navigation Properties foor Book and Person, called People and People1, and Books and Books1 (respectively).
If you select any of these Navigation Properties in the Model Browser and look at the Properties pane, you should be able to see which table is correlated to that association and rename the property appropriately. Here's a screenshot from my PC:
You can see that I've selected the "People" nav property for the "Book" entity. The association in this case is determined by BooksCheckedOutByPeople, so I can rename the property to "PeopleCheckingOut", or something more useful than "People". When I'm using LINQ-to-Entities later, I then reference the "PeopleCheckingOut" property to query that collection on any specific Book.

Resources