Can EF6 use an existing table with GUIDs as the join/bridge table? - asp.net-mvc

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.

Related

Entity framework multiple DbContext in single execution

I have one master & detail in my 'db1' and there is one column named 'EntryByUserId' in master table.
User table is available in 'db2'.
When all the tables are available in one single database we can directly get user detail by using include function. But here my reference table is in another database so in my case user object will return null value. So anyone please help me to achieve this.
I have created multiple dbcontext in my project but don't know how to get this.
Below is the code we use when all tables are available in single database.
dbcontext1.tbl_Master.Include(m => m.tbl_Detail).Include(m => m.tbl_user)
.AsNoTracking().FirstOrDefault();
One option to accommodate this cleanly, especially for something as frequently accessed as a "User" reference for something like reporting on CreatedBy or ModifiedBy tracking on rows would be to implement a view within Db2 that lists the users from Db1. Then in your main application context you can map a User entity to the view rather than a table. I would put guards in your DbContext and entities to discourage/prevent modifications to this User entity, and leave maintenance of users to a DbContext overseeing the Db1 tables.
If this is something like a multi-tenant system with a system database for authentication and separate DBs per tenant which are tracking things like CreatedBy against records, I would recommend considering a system to inspect and replicate users between the auth database and the respective tenant databases. The reason for this would be to help enforce referential integrity for the data and the user references. The issue with the view approach is that there is no constraint available to ensure that a UserId reference actually corresponds with a row in the Users table over in the other database. It can be indexed, but not constrained so you have to handle the possibility of invalid data.

Asp.net mvc5 Identity?

Asp.net mvc 5 Identity 2.0 will create 5 tables automatically when run the mvc project.
Here, my question is why some tables like AspnetUser, it's item 'Id' type defined to string.
The String seems like GUID, but why it doesn't define to guid type instead of using string.
Is it transfer data type from string or do something when quering data ?
I can't figure out why it define to string, but look like guid ?
another table have same problem like AspnetRole, it's item 'UserId', 'RoleId' defined to string too.
Have any idea ?
I'm guessing this is having different reasons.
One reason is the insert performance for Guids, which will get slower and slower after an amount of data (Clustered indexes).
Another reason is the difference of handling Guid in different databases. Microsoft Sql Server has an UniqueIdentifier type that is a Guid, MySql will store them as strings, Oracle stores the raw bytes of a Guid...
I hope this explains a part of your queustion, as not fully :)...
Identity framework not only created for code first approach to be generate database tables with given fields or datatypes. Identity framework can be used against existing database or migrate old asp.net membership provider, or we can use our own table names with extra database fields to store more data on identity tables.
Further more, the Id of the aspnetUser table (that is the User table) used as string because, we can use Guid, integer, long etc. for this field depending on the requirement.
E.g. : If you decided to use integer as Id of the aspnetUser table (User table), then the database field will be auto increment int (or bigInt or etc.) field. But you need to do model binding in order to fulfill entity framework migration requirements.
By default we get Guid inserted into this field when we use out of the box asp.net Identity framework.
When you have defined roles for the registered user, there will be record added into AspnetRole table, this is also completely depending on the fields we defined on the tables as I discussed before. If we decided to use integer as Id of the aspnetUser table, then AspnetRole table fields updated according to the relationship with aspnetUser table fields.
Hope this helps.

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.

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.

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