EF join two tables into one model - c#

Using EF Db first, I have two tables:
Table1: AppId, AppName, AppGuid [PK]
Table2: AppGuid [FK], Description, Url
Can EF create a one entity from the both?
Meaning:
App:
AppId, AppName, AppGuid, Description, Url
Update
Thanks. I have made a view. Mapped it to EF. Now I get the following error: Error 2 Error 111: Properties referred by the Principal Role App must be exactly identical to the key of the EntityType MaMDBModel.App referred to by the Principal Role in the relationship constraint for Relationship MaMDBModel.FK_AppsData_App. Make sure all the key properties are specified in the Principal Role. D:\MaM\Dev\MamAdmin_1.0\MaMDBEntityFramework\MaMModel.edmx 768 11 MaMDBEntityFramework
this is my edmx:
http://ge.tt/3rRWTOR/v/0?c

You can create a VIEW using a JOIN between these 2 tables. After this you can use that View from EF.
Do this in SQL
CREATE VIEW [ViewName] AS
SELECT *
FROM Table1 JOIN Table2 ON Table1.AppGuid = Table2.AppGuid
And import ViewName in your Entity Framework model (as you would do with a normal SQL Table) and use it to query whatever you need
EDIT: Have a look at this link for more info http://www.mssqltips.com/sqlservertip/1990/how-to-use-sql-server-views-with-the-entity-framework/

Related

GetAysnc by Id from many to many Entity Framework

I have 2 tables Center (centerId, name, address,...) and Student (StudentId, NAme, Address) and I determined they have a many-to-many relationship. As a result, I have created a new table CenterStudent (centerId, studentId,...) to join these 2 tables, and I set both centerId, studentId is PK and FK, and cascade delete.
Now I want to get all records with the same studentId. So I wrote
var lists = await studentCenterService.GetAsync(cancellationToken, studentId);
But I get an error
Entity type 'UserCenter' is defined with a 2-part composite key, but 1 values were passed to the 'DbSet.Find' method.
Could anyone give me a solution?
The error seems pretty clear - the .Find() method in EF works only on the complete PK - so if you have a PK made up from two columns (centerId, studentId), you cannot use .Find() to find all entries if you only supply studentId.
You need to use a
UserCenter.Where(x => x.studentId == studentId)
approach instead.

Similar Columns Relation in Entity Framework

I use Entity Framework 4 on C# Winforms.
I have a SQL Server database with 2 tables like this:
Users table:
UserId (int) (PK)
UserName
Products table:
ProductId (int)(PK)
ProductTitle
UserId1 (int) (foreign key referencing `UserId` in `Users` table)
UserId2 (int) (foreign key referencing `UserId` in `Users` table)
I am modeling SQL Server database in my C# project with Entity Framework (including foreign key columns in model).
Then I get records with this code:
Entities dbEnteties = new Entities();
dbEnteties.ContextOptions.LazyLoadingEnabled = false;
var dbe = dbEnteties.Products.Include("Users");
var result = dbe.ToList();
When I get records from database I see that the UserId1 field has data but UserId2 field is Null.
What's wrong with my C# code? And how can I solve this problem?!
It's perfectly okay for you to have two foreign keys in the Products table pointing to the Users table. I do this all the time, and your reason for doing it is fine.
Since you have turned Lazy Loading off, you need to explicitly ".Include" the navigation properties if you want the query to automatically load them. You're going to have to figure out what the names are for the navigation properties that Entity Framework created automatically for you. I'm assuming you are using the "Database First" model. If that's the case, then double click on your .EDMX file and look at the Products table. You should see a section there called "Navigation Properties". They might be called "User" and "User1". If this is the case, then you need to do the following. Since you have two separate relationships between the tables, you will need two separate ".Include" statements:
dbEnteties.Products.Include(product => product.User);
dbEnteties.Products.Include(product => product.User1);
(Make sure to include using System.Data.Entity; at the very top of your file, otherwise the lambda syntax will not work.)

Table name as part of primary key

I have an audit trailing system in my project from http://doddleaudit.codeplex.com/.
As you can see on this image it records the EntityTable - which is the table name, and the EntityTableKey - which is the primary key
I would like to associate the audit records with the tables it had recorder, then query the result in linq to sql. But the problem is if the audit table has record for orders and record for products it will never know just by the primary key, where does the record belong, thus i need to use the table name as part of the key.
So the question is: Is it possible to create a relation that will have a composite primary key that contains the table name in it?
AuditRecord to Orders
AuditRecord to Products
You could do it, but I would recommend a bit different approach.
Don't use char/varchars/nvarchar in your PK/FK, it bloats the index. I would rather create another table that will hold TableId/TableName pairs of all your tables (you can use sys.tables.object_id for your id if you wish) and have a FK in AuditRecords to it. Then establish composite key between AuditRecords and AuditRecordFields (Id, TableId).
Another thing:
EntityTable and AssociationTable should be of sysname type
AuditDate can be of type Date (available from SQL Server 2008)
EDIT:
If you like to access audit records from each object, you can create a base class for your audited objects and implement following method (beware, it's untested):
public IQueryable<AuditRecord> AuditRecords
{
get
{
MyContext ctx = new MyContext();
var ars = from ar in ctx.AuditRecords
where ar.EntityTable.Equals(this.GetType().Name)
select ar;
return ars;
}
}

Code First Entity Model.. Joined Table without Primary Key

im using Code First Entity Model with Web API Asp.Net
i need 3 tables in total
The First table(Table1) contains some information with a unique Id lets say it is like
string id
string model
The second Table (Table2)contains some information about the user. lets say it is
string Id
string name
string company
now i need a third table. which would only work as a joining table and would contain
Table1 ModelInfo
Table2 UserInfo
but it is showing me an error that table cannot be created with out a unique id. but as my architecture is i dont need a unique id
what should i do?
or do i need to change my architecture?
Your question is general EF CodeFirst Many-to-Many relationship.
Suggested readings:
EF CodeFirst - Build Many-to-Many relationships
Composite Key - question on StackOverflow
How to have Many to Many association in EF CodeFirst

LINQ to SQL - No Foreign Keys

No foreign keys defined in the database. So I've setup associations.
problem: can't seem to be able to reference the Role table as expected:
I can get as far as u.UserNamesInRole then can't make the jump to role table.
IEnumerable<fmwebapp1.Old_App_Code.TelerikUsersDataContext.User> userList = (from u in dbTelerik.Users
where u.UsersInRoles.Role.Name = "admin"
select u.UsersInRoles);
where u.UsersInRoles.Role.Name = "admin"
That is incorrect syntax. You need ==.
In a many-to-many relationship, when I want results from one side only, filtered by values on the other side, I usually start my query in the middle of the relation:
To get a role's users:
var users = from ur in context.UsersInRole
where ur.Role.Name == "admin"
select ur.User;
To get a user's roles:
var roles = from ur in context.UsersInRole
where ur.User.UserName == "Jon"
select ur.Role
It would be easiest to add an FK relationship in your database and reimport the tables. EF will then do all the work for you.
If that's not possible, try adding an Association from Role to User and then set the Association Set Name to UsersInRole. Delete the UsersInRole entity from the designer.
You could also compare the EDMX file generated from importing a 'proper' FK relationship between two tables with what you have in your EDMX and then hand edit the XML to match.

Categories

Resources