Entity Framework hides n to n table - asp.net

I have the following tables created using SQL Server management studio (I must not let EF create the DB because I need customized indexing along with something else).
Table A (AId)
Table B (BId)
Table AB(AId, BId)
There are foreign key constrains setup so A - B is a n-n relationship.
Now, when I import the model into EF, the relationship is displayed as * - * (which is correct), but Table AB is gone. This is not what I want! I want to have the ability to manually manage the relationship. How can I have EF show this table?
(the reason is the way EF manage relationship through strongly typed objects is counter performance - e.g. I want to manually create a B and link it to some As (I know the ID) without selecting those As and adding it in B's collection)

As Slauma stated it is possible to add a dummy field, but more importantly you can remove that dummy field and still have the link table.
Simple create the table AB, with an extra column called "Dummy" for example. Generate your model from this table. The table will now be included in the model.
Now got to the database and drop the "Dummy" column.
You can now either refresh the model from the database of simple delete the mapping for the "Dummy" column. You now have the link table in your EF model.

It's not possible to force EF to expose the link table as an entity when you create the model via database first - unless you change the schema in a way that EF does not consider the table as a pure many-to-many link table anymore, for example by adding a "dummy column" to the table. When you are using Code-First however, you can manually create an entity for the link table with two one-to-many relationships between A and AB and between B and AB.
I am not convinced by your argument why you want to do that...
I want to manually create a B and link it to some As (I know the ID)
without selecting those As and adding it in B's collection.
...because you don't need to load any entities from the database if you know the key values. You can use attached stub entities in order to create the relationships and write entries into the link table:
var newB = new B { As = new List<A>() };
foreach (var aId in someAIdCollection)
{
var existingA = new A { Id = aId };
context.As.Attach(existingA);
newB.As.Add(existingA);
}
context.Bs.Add(newB);
context.SaveChanges();
No database query is involved here and the resulting SQL commands are the same like inserting an AB link entity directly.

Related

Reference another table in ASP.NET without a foreign key or joining tables

I have read-only access to a database. This database has multiple tables with status codes and one other reference table the gives a name for each code. These tables are not linked by a foreign key and I can't alter the database in any way. I'd like to display the status names in my web-app view instead of the numeric status code, is there a way to do this? Using EF Core 6
I tried to join the two tables but it didn't match the model in the View. I don't know how to remedy this situation without creating a new table (which I can't do)

Entity Framework 4.1 - select Many to Many Association

I use Entity Framwork 4.1 and MVC 3. My question is about Join tables in Entity Framework.
I created three tables
User - UserId, Username
Role - Role Id, Rolename
UserInRoles- UserId, RoleId
I pulled these tables to my edmx file,
Only two tables appear i.e. the User and Role with a Many to Many Association between two.
If I want to get a user's role from UserInRoles table, What is the approach?
I did something like
var result = (from ar in roles
from au in users
where au.UserName == username
select new {});
This is not working. Please help.
As you guessed, the Entity Framework does combine simple look up tables like that into the parent tables in an effort to help you out. You won't be able to access the look up table in your code, but it will do the heavy lifting and allow you to navigate through the tables like such.
var result = (from ar in roles
where ar.Users.UserName == username
select ar);
Or if you prefer lambdas (personal preference):
var result = context.roles.Where(x => x.Users.UserName == username);
They should be linked I suppose:
var result =
from au in users
where au.UserName == username
select au.Roles;
Not sure if it will give you an empty collection by default. The Roles collection may have to be manually fetched. (Possibly result.Fetch(), but I'm not too familiar with it.)
(Or do you wat access to the actual UserInRole items that are stored in the database?)
Entity framework automatically generates a many to many relationship in the model, when there is only a relationshiptable with one shared primarykey that are foreign keys to other tables.
You can either add another column to this table to add it to your model or generate another unique key for the relationship.
Read more about this here :
http://learnentityframework.com/LearnEntityFramework/tutorials/many-to-many-relationships-in-the-entity-data-model/

Asp.net MVC3 with LINQ to SQL on multiple identical tables

I successfully retrieved data from an already populated table of a live database using mvc3 and linq 2 SQL. The table is defined in the DataClasses1.dbml.
Now I have to retrieve data from other tables with the same identical structure of DataClasses1 but from different databases on the same SQL Server( DB1.Customers DB2.Customers ecc), and display them grouped by database name.
1) How can I do that without creating N DataClassesN.dbml ? I guess since it's the same table structure I can avoid doing it.
2) (Optional): How can I automatically retrieve data also from tables of new created databases?
3) (Not relevant): How can I define a strongly type view? Seems I can do it using EF but I cannot do it using LINQ 2 SQL.
I already thought of creating a view on the database with all the customers tables, but it seems it's a too heavy view!
I have a query that returns all the database names (Select name from master..syttables), is it useful?
Thanks in advance
You just pass a different connection string to the data context when you create it. If the databases are truly identical, including all the foreign key relationships, then just do something like:
var dc = new DataClasses1(db1connectionstring);
// Do your display of database 1 data
var dc2 = new DataClasses1(db2connectionstring);
// Do your display of database 2 data
I have no idea what you mean by #2. Data doesn't retrieve itself.
You can't obviously join results from 2 databases in SQL so you'd probably have to use 2 queries (one to each database) with one of them selecting into a new Entity of the other database and then join the results in memory using LINQ afterwards. So one query returns DB1.EntityName and the other returns DB2.EntityName but with a select mapping this to new DB1.EntityName entities and then join the two. It's not a pretty solution but is the best I can think of off the top of my head.
If you just want each database to have a set of results each then obvioulsy you can just return 2 result sets. Let me know if I misunderstood your question.

Entity Framework - Use join table to return collections of Followers / Following

Using Entity Framework, I am writing a social networking app and trying to setup some relationships so that I can have Users with Followers/Following properties.
I have a Users table:
Users
_______
Id
FirstName
LastName
Email
Then I have a Follows table:
Follows
__________
FollowerId
FolloweeId
On a strongly typed User object, I want to see .Followers and .Following properties that return collections of User objects. So far I've tried making the columns in the Follows table as foreign keys, and both as composite primary keys. The entity model comes out the way I want it (I don't have an Entity in-between, and I just have to rename the navigation properties), but when I populate with data, the Followers and Following collections are empty, so something is not right with the relationships.
I suppose I could separate and have two tables, Followers and Following, but I would have duplicate data and would have to add to two tables when someone follows someone else.
You need to include the data for the tables you User tables has relationships with in your query.
A query like this:
using (EntityObject context = new EntityObject())
{
var user = from x in context.users.Include("Followers").Include("Followees") //use your tables
where x.Id == TheUserId
select x;
}
Will let you have access to the objects for those included tables.

insert data from a asp.net form to a sql database with foreign key constraints

i have two tables
asset employee
assetid-pk empid-pk
empid-fk
now, i have a form to populate the asset table but it cant because of the foreign key constraint..
what to do?
thx
Tk
Foreign keys are created for a good reason - to prevent orphan rows at a minimum. Create the corresponding parent and then use the appropriate value as the foreign key value on the child table.
You should think about this update as a series of SQL statements, not just one statement. You'll process the statements in order of dependency, see example.
Asset
PK AssetID
AssetName
FK EmployeeID
etc...
Employee
PK EmployeeID
EmployeeName
etc...
If you want to "add" a new asset, you'll first need to know which employee it will be assigned to. If it will be assigned to a new employee, you'll need to add them first.
Here is an example of adding a asset named 'BOOK' for a new employee named 'Zach'.
DECLARE #EmployeeFK AS INT;
INSERT (EmployeeName) VALUES ('Zach') INTO EMPLOYEE;
SELECT #EmployeeFK = ##IDENTITY;
INSERT (AssetName, EmployeeID) VALUES ('BOOK',#EmployeeFK) INTO ASSET;
The important thing to notice above, is that we grab the new identity (aka: EmployeeID) assigned to 'Zach', so we can use it when we add the new asset.
If I understand you correctly, are you trying to build the data graph locally before persisting to the data? That is, create the parent and child records within the application and persist it all at once?
There are a couple approaches to this. One approach people take is to use GUIDs as the unique identifiers for the data. That way you don't need to get the next ID from the database, you can just create the graph locally and persist the whole thing. There's been a debate on this approach between software and database for a long time, because while it makes a lot of sense in many ways (hit the database less often, maintain relationships before persisting, uniquely identify data across systems) it turns out to be a significant resource hit on the database.
Another approach is to use an ORM that will handle the persistence mapping for you. Something like NHibernate, for example. You would create your parent object and the child objects would just be properties on that. They wouldn't have any concept of foreign keys and IDs and such, they'd just be objects in code related by being set as properties on each other (such as a "blog post" object with a generic collection of "comment" objects, etc.). This graph would be handed off to the ORM which would use its knowledge of the mapping between the objects and the persistence to send it off to the database in the correct order, perhaps giving back the same object but with ID numbers populated.
Or is this not what you're asking? It's a little unclear, to be honest.

Resources