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

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!

Related

rename domain class, groovy and grails reverse engineering

How do a rename a domain class while reverse engineering or after reverse engineering.
i generated class using reverse engineering in Groovy and Grails.
the domain class name was AgentTable. I want to rename it as Agent. When i renamed the domain class using IntelliJ (right click - refactor - rename), it renamed the AgentTable to Agent whereever it was used. but when i start the server (run the app), giving error
"nested exception is org.hibernate.HibernateException: Missing table: agent"
I have to do this for few domain class. is it anyway i can give an alternative name while reverse engineering the domain classes.
or after domain class was created how do i rename it without this error.
Look into your database the name of the table it created for the agent. Once you know the name of the table add the following in your new domain
static mapping = {
table "table-name-here"
}
While it works I would not recommend #elixir 's approach.
In my opinion the mapping is not supposed to be used for renames. This is also how I understand the official documentation.
In the example they use it to map Person onto the 'people' table, not because of a rename but because of a semantic reason. Tables are typically named after the plural form. Here is a nice answer on another question regarding this. In the project I am working on the domain object 'User' is mapped to the table 'users'. You can not use the table name 'user' as it is an SQL statement.
Assumptions and clarifications:
In my experience Grails maps the domain name to the table name after these rules (example domain name 'MyExampleDomain':
separate the domain name by capital letters (My Example Domain)
lower case all (my example domain)
replace spaces with underlines (my_example_domain)
Following this your Domain Class 'AgentTable' has a table 'agent_table' in your respective database. After your rename Grails even tells you what it wants:
nested exception is org.hibernate.HibernateException: Missing table: agent
It wants to look up values in a table called 'agent' but it can not find it. The refactor function of IntelliJ does not rename the functions, so it will miss out on the database.
Luckily we know exactly what values it wants - the values previously found in 'agent_table'.
So why create this confusion with remapping domains and table names when we could just rename the table and be done with it?
The solution:
Execute an SQL script like this on your database:
ALTER TABLE <old_domain_name> RENAME TO <new_domain_name>;
The names are of course in their "table-form".
This simply renames your table to match the expected format in Grails. When restarting everything should be fine.
However you do not need to use rename. You could also create a whole new table, build it the way the domain objects wants it to be and then migrate the data. See section 'Problems with this approach' for information on when to use what.
Problems with this approach:
As always, tinkering with information a program depends on (and even generated itself) will often have some dire consequences if you aren't careful.
For example we have to pay attention to keys. If your domain object has a relation to other objects it will hold them in the table via foreign keys. Depending on how you chose to migrate the information in the table you might have deleted these foreign keys connections. You will have to add them via a separate SQL statement. When you choose to recreate the table this will happen for sure. Renaming it should keep the keys.
Another one are column names. If you choose to rename attributes you will also have to rename the columns via SQL. You will also have to remember the foreign keys other tables might have on the table you are renaming. RENAME did this automatically for me, but you should double check.
Why you should still stick with this approach:
Remapping domain objects to the tables with old names is bound to create code smell and confusion. Do you really want to remember these mappings in your head? And more importantly: do you really expect other people to have to work with this?
The best case is if people can't even tell if this object has ever had a different name and changing the database is the best way I know to achieve this.

Creating Model in Entity Framework

I am creating models in Entity Framework. I am trying to insert records in tblOffStrategy. In tblOffStrategy, OffId is Foreign Key and OffId and BonusStrategy are composite keys. DBA's creates table for us so I am creating model based on tables.
When I add-migration from Package Manager Console, I am getting "Unable to determine composite primary key ordering, Use the ColumnAttribute". Also I am not sure if my Foreign Key relationship is working.
Would anyone take a look at it and point me to right direction? Any help will be appreciated

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?

Foreign keys not working in link table in Linq2Sql

I have 3 tables Subcontract, Company, and a link table CompanyToSubcontract. The link table contains the Subcontract_id and the Company_id. The foreign keys were set-up in SQL and when I drug them into my dbml the one-to-many relationship arrows showed up and everything looked fine. However, when coding, it's as if the relationship isn't there.
When I write a Select statement I have to use the join for it to work. When I refer to CompanyToSubcontract in code, I don't have the correct members available. I have CompanyToSubcontract.company_id and CompanyToSubcontract.subcontract_id, but not CompanyToSubcontract.company or CompanyToSubcontract.subcontract.
I have another table Group which has a one-to-many relationship with Subcontracts. I set up the foreign key the same way and that's working great. I can access Subcontract.group_id as well as Subcontract.group.
Everything seems to be set up properly for the link table, but I cannot get it to work. Is there some kind of trick for multiple foreign keys? What am I missing?
EDIT: My CompanyToSubcontract doesn't have a primary key. Could that be causing the problem? Trying it right now.
That was it. I needed a primary key on the link table.

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