ASP.net 4.0 Entity Data Model Mysql Not Treating Mysql Enums Right - asp.net

I just starting learning, testing ADO.net Entity Data Models with MySql - everything is going fantastic except i've noticed one thing..
In my MySql table i've created an Enum column type. When ASP.net creates the Model classes the enums are treated as strings and not as Enums - is there a way to fix this?
UserStatus column in MySql is an Enum that has 2 potential properties, Enabled and Disabled - however asp.net treats as string value:
user.UserStatus = "Enabled";
Was hoping to see something along these lines...
user.UserStatus = UserStatuses.Enabled;
Thanks!!
Loren

There's no such thing as an enum sql type, at least not a standard type, which means it's non-standard and you'll have a hard time finding any framework that properly supports it properly.
To make matters worse, Entity Framework does not currently support Enum types in code either. There are some hacks and workarounds, but you will find them to be painful and not worth it. For all intents and purposes, a MySQL enum is a string object. You may have to issue some custom sql to get the enum types to populate your listbox though.
Oh, and FYI: 8 Reasons why MySQL's ENUM data type is evil

Related

entity framework core exception handling db first

Background
With ef core code first approach, validation is robust and simple: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/validation
With the database first approach, it seems like any validation is happening behind the scenes by the database when dbcontext.SaveChanges(); is called. What's worse, these exceptions are nebulous and entirely unhelpful, for example, SqlException: String or binary data would be truncated can be thrown if any of the string properties of any of the entities have too many chars (ours is a legacy app riddled with char(10) and such), or even if a key that is a string is left null.
Question
I want to know if there is any reasonable or accepted way of enforcing the validation. I've found this question which might help debugging, but I would like to enforce the constraints in code
Is there any better method than changing every auto property to one that throws if it's constraints aren't met?
EntityFramework Core does not enforce any validation at all. The validation rules you see in the example are enforced by MVC and not EF. One of the main reason for EF Core to remove validation check was that only. Validation are run in UI and then in EF and then again in database which is just redundant. Hence client side validation is left to the front-end (MVC in this case) and server side is done by database engine.
When you use database first approach, EF core does not generate any annotation for validation because it does not reason about them anyway. That means you would get only server side validation which means error during SaveChanges.
The only way to enforce constraint in the code (client side) is to write those annotations so that MVC can enforce them or write custom code to deal with it. The whole validation mechanism is transparent to EF.
I ended up going with a psuedo extension to the generator tooling. Since the DBContext is a partial class, I made a new class that has a main
public partial class DBContext{
public static void Main(string[]args){
DBContext context = new DBContext();
var modelbuilder = new Microsoft.EntityFrameworkCore.ModelBuilder(new Microsoft.EntityFrameworkCore.Metadata.Conventions.ConventionSet());
context.OnModelCreating(modelbuilder);
IMutableModel model=modelbuilder.Model;
from there I used Linq to transform the various info about each entity's properties and the annotations on them into List<KeyValuePair<string,List<KeyValuePair<Regex,string>>>> where the first pair's key is the entity name, and the value is a list of find and replace pairs to edit the code that had already been generated with the corresponding validation, one per property. Then all I had to do was abuse the fact that the tooling generates the classes in <className>.cs files, and iterate over my list, executing the replacements for each entity source code file.
I'd have preferred doing something a little less hacky, because I'm relying on format that the ef tooling outputs, but it works

Enum naming to avoid name clashes

I'm trying to standardise the way I name things, but as a newbie I always seem to come up with an issue somewhere further down the line.
Case in point - I have a user control and enum that clash. The UC is very specific and contains a form dropdownlist/validation for customer input - the name relates to the type of input so the class is named EmploymentStatus.
However, the dropdownlist is populated via an enum - ideally this would be called EmploymentStatus too as I've adopted the recommended singular form for enums.
No doubt everyone has come across this issue at some point, but what is a good solution?
I think namespaces would be the way to go here. Just put the enum in a separate namespace then refer to fully qualified e.g.
MyCompany.MyApplication.AnotherNamespacePart.EmploymentStatus
If this is a bit verbose then you can use namespace aliases to make things a bit more readable.
using myEnum = MyCompany.MyApplication.AnotherNamespacePart;
... some code
myEnum.EmploymentStatus
Please note I've assumed C# here but the principle will hold for other asp.net languages
In my humble opinion and all that

Updating Role description (entity framework / LINQ)?

Mates, I want to update a role description using my application
I donĀ“t know what is the better way to connect to the database and run a UPDATE statement.
Would it be Entity Framework? LINQ? None of this 2 options..
Please, suggestions.
I would say that Entity Framework would be currently the best solution for you. Not only it is strongly supported by Microsoft (well Silverlight was as well) but:
If you start with it, you can use designer. It's graphical UI will guide you when generating the model (based on database) or generating the database schema when starting with model.
Read some tutorials abut it:
http://msdn.microsoft.com/en-us/data/ee712907
And later take a look how to use some more profesionla techniques as Repository pattern or unit of work
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
Not Linq ..well yes linq, but linq is the querying framework where as entity framework is the object relational mapper. So Both actually. You could do this in various other ways but those two technologies work very well together from my experience.
In Visual studio you would create a new ADO.NET project template which you then hook up to your database. and then you can update the tables and do a whole bunch of stuff. Linq is build into .NET so technically you can query any objects using linq ( which makes it so much fun ) and because your entity is an object you just reference it ( first declare it ) and then play with it
FooModel foo = new FooModel(); // Entity
var fooQuery = from _ in foo.DescriptionTable // Linq query
where _.Description == SelectedDesc // table selection query
select _;
foo.Add(fooQuery); // add to database
foo.SaveChanges(); // save changes
Something like that. There is a bit more to it that would project specific but you would have to give more details.
It is most certainly worth learning both technologies and have doubt you will find them very useful. Both can get very complex but for what you need it for you just need the basics down and then you can explore from there.

Entity Framework for Multi-tenant architecture - filterings single table by tenant ID

We are looking for a way of automatically filtering all CRUD operations by a tenant ID in Entity Framework.
The ideas we thought of were:
Using table valued user defined functions
Using stored procedures (but we don't really want to, as we're using an ORM to avoid doing so)
Some how modifying the templates used to generate the SQL to add a where clause on each statement.
Some how modifying the templates used to generate the LINQ in the controllers (we may use MVC).
Any tips?
-thanks
Alex.
Using table valued user defined functions
Table valued function are only available in .NET 4.5 Beta (and not available in code first). Using them will still not help you because you will have to use the function in every LINQ query so it is the same as using where clause.
Using stored procedures (but we don't really want to, as we're using an ORM to avoid doing so)
It can be useful for some special complex queries but generally it is not what you want.
Some how modifying the templates used to generate the SQL to add a where clause on each statement.
Too complex and on completely different level of abstraction.
Some how modifying the templates used to generate the LINQ in the controllers (we may use MVC).
Close to ideal solution. You simply need to wrap access to your entity set into some code which will look like:
public class MultiTenantAccess<T> where T : IMultitenant
{
private IDbSet<T> set;
...
public IQueryable<T> GetQuery(int tenantID)
{
return set.Where(e => e.TenantID == tenantID);
}
}
Sometimes this is core for something called Generic repository but it is really just a wrapper around EF set. You will always use GetQuery to query your data store instead of using DbSet directly.
you may also separate the tenants data into different databases
or into same database, but with different schemas? You can read more about this in an old MSDN article called "Multi-Tenant Data Architecture"

Asp.net Entity Framework and generated SQL problem

I have a problem with the following Linq query using Entity Framework:
from o in ctx.Entity
where o.EntityID = entityid
select o;
Simple enough right? Well the 'Entity' set is the parent class of a whole lot of other classes. The generated SQL for this simple query is about 20K worth of characters with a slew of 'case' and 'union'. In addition of taking a while for the framework to compile the query, it takes a while to execute too.
So how can I improve the SQL generated by the framework in case of queries using classes with heritage? Or what other technique can I use to avoid this problem?
AD
The reason it is doing that is because of the relationships of Entity with other tables in your database. To cut down on that, you need to read up on how to better control the explicit/lazy loading of references that EF is doing for you
http://blogs.msdn.com/jkowalski/archive/2008/05/12/transparent-lazy-loading-for-entity-framework-part-1.aspx
No post like this would be complete without a plug for nhibernate, which is more powerful/robust/performant/and easier to use ;-) but hopefully that link will help you out

Resources