Automatic Model Validation When Generating the Models using Entity Framework Database First Approach - entity-framework

Consider the following property UserName of a Model Class. You can see that the validation criteria are added over it manually.
[Required]
[StringLength(100, MinimumLength = 6)]
public string UserName { get; set; }
Now again consider the following code:
public string UserName { get; set; }
The same property without the validators. Now when I am generating the model class using Entity Framework Database first approach I am getting the later result (means a property without having validators). But in the database there are constraints added over each attribute.
So is there any tool/way that I can use those constraints and generate the model class having properties like shown in code 1 (that is property with validators).

No there is no ready to use tool which would add these attributes for you. You can modify T4 template to create these attributes for you but for that you need to understand how EF metadata are stored. You can add attributes yourselves manually in buddy classes.

Related

Entity Framework - Database generated identity is not populated after save if it is not the key of the entity

I have a model like
public class MyEntity
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public int Id { get; set; } // Id
[Required]
[Key]
public System.Guid GUID { get; set; }
}
The GUID property is the PK by design, but I have a db generated Id property that I use within my code to determine if the object is a new object that hasn't been saved yet.
When I save this object with Entity Framework, the Id property does not get back populated as normally happens for database generated properties (although usually these are keys). I have to query the DB for the object and grab the ID manually. It seems EF only back populates Key properties on SaveChanges.
Is there any way to get EF to automatically populate the Id property here? Setting it as the Key is not an option, I have dozens of tables that are FK'd to the GUID property and for good reason.
EDIT: I have discovered that the package https://entityframework-extensions.net/ is handling my save changes. If I use the standard EF savechanges it works, but not with the extensions version.
Disclaimer: I'm the owner of Entity Framework Extensions
It was indeed an issue in our library. This scenario was not yet supported for EF6.
However, starting from the v4.0.50, it should now work as expected.

Entity Framework association with Data Annotations in MVC

I am a newbie in EF, i created a demo application in which i Assigned [StringLength] attribute to model.
[Required]
[StringLength(10)]
public string CustomerName { get; set; }
This worked fine with my EF-Code First approach.
But if i am removing this attribute, then the EF is throwing exception.
I want to know the association which EF created with these attributes
StringLength attribute can be applied to a string type property of a class. EF Code-First will set the size of a column as specified in StringLength attribute. Note that it can also be used with ASP.Net MVC as a validation attribute.
Source
When you don't specify a length, EF Code-First will generate a VARCHAR(MAX)column for your strings. Thats the missmatch you get when you first create the column with StringLength(10) and remove it afterwards.

how to generate a database table from an entity type?

How to create an entity type and then generate a database table from it?
I know this feature was not supported two years ago in EF, what about now?
You've got 2 options:
Entity Framework Model First where you create the model first and then generate the database from that or
Entity Framework Code First where you create normal Poco objects and generate the database from that.
I've personally used Entity Framework Code First for MVC development and it works like a charm, it really is an awesome feature and easy to use.
Now, Entity Framework introduced these feature.
Basically, with only two steps is sufficient for this, please see below steps to go:
Create your Entity
public class Resturant
{
public int ID { get; set; }
public string Name { get; set; }
}
Create Context class
public class OdeToFoodDb: DbContext
{
public DbSet<Resturant> Resturants { get; set; }
}
However, you may need more coding in Global.ascx for advance options but these are the basic steps.
A database named "OdeToFoodDb" will create and a table named "Resturant" also will create by these steps.

Why is entity framework not annotating some non nullable columns as required?

I am using EF 4.1 with database first.
Example table:
CREATE TABLE dbo.Foo(
[ID] [int] IDENTITY(1,1) NOT NULL,
Created datetime not null default(getdate()),
Title varchar(80) not null
PRIMARY KEY CLUSTERED ([ID] ASC)
)
EF correctly loads the model with all 3 columns as nullable = false.
Output from code generation item "ADO.NET DbContext Generator":
public partial class Foo
{
public int ID { get; set; }
public System.DateTime Created { get; set; }
public string Title { get; set; }
}
In MVC3 I generate the FooController via the db context and foo model. When I bring up /Foo/Create and hit "Create" on the blank form it shows a validation error on "Created" field but not on "Title".
If I enter only a "created" date I get an exception:
Validation failed for one or more entities. See 'EntityValidationErrors'
property for more details
The exception is "The Title field is required".
I'm not sure why it works fine for one column but not the other. My first fix was to simply add the annotation, however the class code is auto generated by EF.
The only fix that seems to work is to use a partial metadata class: ASP.NET MVC3 - Data Annotations with EF Database First (ObjectConext, DbContext)
I can add the [Required] tag as desired however this should be unnecessary. Is this a bug in EF or am I just missing something?
This isn't a bug, EF simply doesn't add those attributes. As far as i know, the database-first approach (Entity classes generated by the designer) doesn't even perform the validation. The link you're refering to is a valid solution for your problem. The principle of buddy-classes which contain the actual metadata was introduced due to the fact, that you cannot add attributes to existing properties in a partial class.
The code-first approach has a built-in functionality to validate your annotations, see: Entity Framework 4.1 Validation. Another solution when using database-first would be to create a custom code-generator that applies those attributes T4 Templates and the Entity Framework.

Entity Framework 4 with Existing Domain Model

Im currently looking at migrating from fluent nHibernate to ADO.Net Entity Framework 4.
I have a project containing the domain model (pocos) which I was using for nHibernate mappings. Ive read in blogs that it is possible to use my existing domain model with EF4 but ive seen no examples of it. Ive seen examples of T4 code generation with EF4 but havent come accross an example which shows how to use existing domain model objects with EF4. Im a newby with EF4 and would like to see some samples on how to get this done.
Thanks
Aiyaz
Quick walkthrough :
Create an entity data model (.edmx) in Visual Studio, and clear the "custom tool" property of the edmx file to prevent code generation
Create the entities in your entity data model with the same names as your domain classes. The entity properties should also have the same names and types as in the domain classes
Create a class inherited from ObjectContext to expose the entities (typically in the same project as the .edmx file)
In that class, create a property of type ObjectSet<TEntity> for each of you entities
Sample code :
public class SalesContext : ObjectContext
{
public SalesContext(string connectionString, string defaultContainerName)
: base(connectionString, defaultContainerName)
{
this.Customers = CreateObjectSet<Customer>();
this.Products = CreateObjectSet<Product>();
this.Orders = CreateObjectSet<Order>();
this.OrderDetails = CreateObjectSet<OrderDetail>();
}
public ObjectSet<Customer> Customers { get; private set; }
public ObjectSet<Product> Products { get; private set; }
public ObjectSet<Order> Orders { get; private set; }
public ObjectSet<OrderDetail> OrderDetails { get; private set; }
}
That's about it...
Important notice : if you use the automatic proxy creation for change tracking (ContextOptions.ProxyCreationEnabled, which is true by default), the properties of your domain classes must be virtual. This is necessary because the proxies generated by EF 4.0 will override them to implement change tracking.
If you don't want to use automatic proxy creation, you will need to handle change tracking yourself. See this MSDN page for details