Is there a way to make Entity Framework Core map all Guid properties to nvarchar without annotations? - ef-core-2.0

I have a domain model that makes use of Guids for primary/foreign keys. Is there a way to instruct the ModelBuilder to explicitly create database tables with nvarchar storage for these properties without applying annotations on every existing primary and foreign key in my entity classes?

Use the Microsoft.EntityFrameworkCore.Storage.ValueConversion.GuidToStringConverter value converter.
var guidToStringConverter = new GuidToStringConverter();
modelBuilder.Entity<YourEntity>()
.Property(ye => ye.PropertyThatIsAGuid)
.HasConversion(guidToStringConverter);

Related

Is it possible to make Entity Framework insert primary key that I given?

I forced to work with database where tables haven't auto increment. And I can't alter it. I want to insert entity using Entity Framework. I create an object of this entity and manually set it's Id field (primay key) and then make Add and SaveChanges. But I see in log, that EF clear the value of DbParameter for Id field. Is there any solution for this?
You can add an annotation of fluent configuration to tell EF the keys are manual. See Entering keys manually with Entity Framework. You could also add a custom convention to handle globally: Convention for DatabaseGeneratedOption.None

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.

Entity Framework: how do I add a field to my entity to match the store procedure result

I have an entity (Org) in my Entity Framework that has a foreign key with a table that is in another database (BusinessUnit). We need the foreign key to get the description of the BusinessUnit linked with the Org. In the past (old project without Entity Framework) we were using a stored procedure to return all the information about this entity, including the BusinessUnit description, using a join. So now my problem is how to display the same information than before using Entity Framework.
I've tried, once I load my Org entity from database, to make a loop accessing to BusinessUnit to get the description for each Org, but this is too slow. My other idea was use a store procedure, but I need an extra field on my entity and Entity Frameworks gives me an 3004 error: No mapping specified for my property. I was thinking to use a complex type, but I'm not sure if it's what I need keeping in mind I have to add just a field to my entity. In that case, could I use the complex type just for "select" operations and keep my original entity for the rest of CRUD operations?
How should I proceed?
Thanks.
EF is not able to execute queries across multiple databases. If you need to perform such query you must either use database view and map the view as a new entity (it will be readonly - making it updatable requires mapping insert, update and delete stored procedures) or divide your data querying into two separate parts to load data from both databases. Divided querying can either use two contexts or you can get data from the second database using stored procedure.
The reason why you got the error is that you added the property in EDMX. EDMX can contain only properties mapped to your first database. EDMX generates entity code as partial classes If you need property manually populated from the second database you have to create your partial part (partial class) for entity and add the property in code.

Object Generated From Entity Model Does Not Create Nullable Foreign Keys

I have noticed some strange behavior when it comes to nullable foreign keys in my database. I have just started playing with the entity framework so I'm probably doing something wrong, but I cannot figure this one out.
Say I have the following two tables: (CountryID is a foreign key that is nullable)
When I create a new entity model I end up with this:
But the CountryID properties are set to Nullable (None) - instead of True. Obviously this is a really trivial example, but with a large database it would be difficult switch all of these manually. Is there any way to have the entity framework use a nullable int? for these foreign keys?

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