Entity Framework association with Data Annotations in MVC - entity-framework

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.

Related

How to add Foreign Key Properties subsequently to a Code First Model?

Given the Model:
Public Class Customer
Property Id() As Guid
Property FirstName() As String
Property MiddleName() As String
Property LastName() As String
Property Addresses() As ICollection(Of Address)
End Class
Public Class Address
Property Id() As Guid
Property Name() As String
Property Street() As String
Property City() As String
Property Zip() As String
Public Property Customer() As Customer
End Class
Entity Framework 6 Code First has created a column called Customer_Id in my table Addresses. Now, I'd like to add a Property Customer_Id to my class Address that represents the existing foreign key relation:
Public Class Address
Property Id() As Guid
Property Name() As String
Property Street() As String
Property City() As String
Property Zip() As String
Public Property Customer() As Customer
//Added
Public Property Customer_Id() As Guid
End Class
Unfortunately this results in an InvalidOperationException while creating the DbContext saying:
The model backing the 'DataContext' context has changed since the database was created.
I tried different property names (with and without underscore, different casing). But still no luck. So, what is the correct way to add those properties subsequently without the need for migrations? I assume it's possible, because the model does not really change, I am only changing from an implicit declaration of a property to an explicit...
Update:
The responses show me, that I did not explain the problem very well. After some more reading I found the correct names now: I have an application which is installed several times at customer locations (therefore dropping and recreating the database is no option). Currently, it depends on Entity Framework's Independent Associations, but I want to have the Foreign Key in my entity as well (this is no change to the model, the foreign key is already there, but does not exist as a property in my entity, since this is currently only relying on the IA instead). I did not manage to add it without EF thinking my Database is outdated.
for me two ways :
drop table __MigrationHistory : that is have the new model runs, but forget migration functionalities
create a new db by changing the connection string of the application. Replace old __MigrationHistory by __MigrationHistory of the newly created db
Never tested the second solution, but it should work.
Before using any solution:
backup you db.
Before using first solution: are you sure you will never need migration functionalities ?
This exception is because you change your model. You have to set migration strategy. Please look at:
http://msdn.microsoft.com/en-us/data/jj591621#enabling
(edited)
First of all you have to remove that exception. Even if you didn't add any new column to your database your model has changed because you added new property to Address class. If you check your DB you will find dbo.__MigrationHistory table with Model column. Last (earliest) value from that column is used for checking that your model and DB are compatible. I'm not sure but I think that EF stores there binary serialized model. So the solution is - recreate DB or add migration (probably empty migration).
(edited)
When you want to set FK you can do this very simple by Data Annotations
// c# example
public class Address
{
...
public string CustomerId { get; set; }
[ForeignKey("CustomerId")]
public Customer Customer { get; set; }
}
or in fluent api
// c# example
modelBuilder.Entity<Address>()
.HasRequired(arg => arg.Customer)
.WithMany()
.HasForeignKey(arg => arg.CustomerId);
or look at:
http://weblogs.asp.net/manavi/archive/2011/05/01/associations-in-ef-4-1-code-first-part-5-one-to-one-foreign-key-associations.aspx
http://msdn.microsoft.com/en-us/data/hh134698.aspx

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

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.

How to add unique non primary-key field to entity using Entity Framework 4.1?

We are using Entity Framework 4.1 Code first.
We've got user entity with primary key set to UserId and need UserLogin to be unique. How can it be done?
Entity Framework does not support Unique constraints. You can create them using a SQL Query to generate unique constrains when initializing the database. Write your custom initializer for the model and execute SQL command to generate constrain.
Edit
Now (EF 6.1 onwards )you can easily have unique constrains ,
[Index("UserLoginIndex", IsUnique = True)]
public string UserLogin { get; set; }
Check out the unique constraints, I think that's what you're looking for?
http://weblogs.asp.net/manavi/archive/2011/01/23/associations-in-ef-code-first-ctp5-part-3-one-to-one-foreign-key-associations.aspx

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.

What is the meaning of the "Pluralize or singularize generated object names" setting?

When setting up a new Entity data Model, there is an option to
[x] Pluralize or singularize generated object names
I have noticed this is an option in LINQ as well. Also, now that I am studying the ADO.NET entity framework, I noticed it also has 'DEFAULT' to 'pluralize or singularize generated object names'
What is the result of not checking/allowing this option when setting up the 'Entity Data Model'.
What Advantages/Disadvantages/issues will I face by making a selection one way or the other?
If you check Pluralize or singularize generated object names, the set in the class context.cs genrated by EF will be named in the format:
public virtual DbSet<SomeTableName> SomeTableNames { get; set; }
if not check, it'll be named:
public virtual DbSet<SomeTableName> SomeTableName { get; set; }
Advantages/Disadvantages IMHO:
I would like to see collection set be named ending with 's', such as dbset colleciton of Employee class of Employee Table named Employees, so I'll check the option. But I guess maybe someone would like to treat the dbset as a table, so he/she would like to name it same as table name Employee.
No problem at all, except that you'll probably want to do it manually. Usually, you want entity names singular and entity set names plural.