Entity Framework 6 -required properties - entity-framework-6

I am developing a project in asp.net mvc 5 + EF6. All my entities have been modeled the way they should....I have repeated this process several times in my project, now I am having and issue with [required] properties. Let's say for instance, I have 10 properties in my model class from which 4 of them I have marked as {Required]...so, the other 6 properties can allow nullable values...aren't validated in my model, so the user doesn't have to provide a value for those properties in the view...just the required ones are mandatory.
The thing is that there are some properties apart from those I set up as Required that are also required despite I didn't do it...in my model just 4 properties are marked required...but in my view somehow is validated as required more than 4 properties...
When I check my migration file related to that model change..I have realized that those properties I am refering apear this way:
...
ContactName = c.String(nullable: false, maxLength: 50),
...
I'm afraid that is I change this migration file, and set nullable to true, or drop the the entire info between paretheses and rerun the migration I will get an error since EF will try to create a table that already exist.
Someone could tell me what's happening...and a possible solution..
Thanks.

Related

Entity Framework saving a property with [ReadOnly(true)] Metadata

MVC 5 EF 6.
I've created an edit page using Scaffolding. Saving works fine until I want to restrict the editing of certain properties.
I didn't just use:
#Html.HiddenFor(model => model.Property)
as I wanted the fields to still be visible in the UI. and I didn't want to make it uneditable in the view as it's not really MVC - I wanted to control the editing of the Property from the Model (this is a field that should NEVER be changed but isn't the primary key).
I've implemented the solution from here: How to create readonly textbox in ASP.NET MVC3 Razor and it works perfectly. I can use the annotation:
[ReadOnly(true)]
on my Properties in the model and know that which ever view the property is displayed, it won't be editable.
I thought I had the perfect solution, until I clicked save and get the error:
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
Using SQL profiler I have found that using the annotation [ReadOnly(true)] means that NULL will be sent to the database for saving.
Does anyone know why this happens, and is there anything I can do that will allow me to carry on in the way I think is a good solution for displaying data I don't want edited and controlling this in the Model.
Any other suggestions of achieving the same are welcome - or reasons why my whole design is flawed.
If you set the the property with ReadOnly when you press save the model binding will not get the value for readonly for a security reason, let's say if someone removes the readonly attribute through the developer console, then it will enable the field enabling edition, then it's not readonly anymore , that's why you are receiving null on the server ( model binding ), the right why it's to get the value of the readonly again on the server before persisting on the DB
in a few words, the readonly it's working fine as it should be

Prevent EF6 from generate navigation properties

I've recently started to use EF6 and i'm building a couple of T4 templates to generate some code automatically (on VS2012).
I'm generating my model from the database and this process creates all the associations automatically based on the DB ForeignKeys. And generates too a "Navigation Property" for that field in Associations/FK.
I want to get a "Flat Version" of my entities without navigation properties. Just a class with properties corresponding to table columns.
Is there any way to "Generate Model from Database" and get this? i've tried to update model with the option "Include foreign key columns in the Model" unchecked, but the associations and nav props are still being generated.
thanks in advance
You must edit the t4 template that builds the model classes to get this done.
In your project you'll find two .tt files, something like ModelName.Context.tt and ModelName.tt. The latter is the one that builds the model classes.
Look for these two lines
this.<#=code.Escape(navigationProperty)#> = new HashSet<<#=typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType())#>>();
(probably around line 50)
and
<#=codeStringGenerator.NavigationProperty(navigationProperty)#>
(probably around line 100)
and erase these lines.
Now when you save the template, your classes will be re-generated without navigation properties.
SOLUTION FOUND
As i was reading the conceptual model, i was getting innaccurated information about the table structure, because the conceptual model on the edmx, because when we have foreign keys, associations are created and Nav props instead of regular property (on the fields withing the FK).
The solution i Found is use the store model instead of Conceptual model
Getting the Conceptual Model "Wrong way"
MetadataLoader loader = new MetadataLoader(this);
EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);
Getting the Store Model "GOOD way"
MetadataLoader loader = new MetadataLoader(this);
StoreItemCollection ItemCollection = null;
loader.TryCreateStoreItemCollection(inputFile, out ItemCollection);

Grails domain class Constraints vs Legacy DB constraints

I am using grails GORM for database mapping and oracle as database which is already populated with values.My question is can I define a new constraint like Foreign key in the domain class even if its not defined in the underlying table in my legacy db?The grails app is still going to accept the constraints right?The constraints dont have to exactly match those of database right?
you can define attributes of a class, which are not saved in the db and due to this don't need a representation in the db these attributes are defined as follows:
class Person {
String name
static transients = ['name']
}
see information about transients. In 2.x transients are not auto-bound as listed in the docs here, so you have to do a bindable: true explicitly.
Yes, the constraints you define in your domain class will be respected regardless of what you have in your database. The only time the 2 really relate is if you are letting Hibernate generate DDL for you (which most folks do not do for their production environment) in which case there are certain constraints which affect the DDL that is generated. Since you already have a database you almost certainly have that turned off.
EDIT:
An example of a constraint which affects DDL is the size constraint. If you constrain a String field with something like size: 5..15, by default the DDL that is generated will create a column that is 15 characters wide. If you are not allowing the app to generate DDL that constraint is still applied at validation time and if the property has more than 15 characters or fewer than 5, validation will fail. Once validation passes and the data is sent to the database, the framework assumes everything will be ok there. If it isn't, then corresponding exceptions may be thrown. For example, if the String has 12 characters it will pass validation in the app and will be sent to the database. If the database column is only 8 characters wide, you are going to get a SQLException. I hope that makes sense.

How does Breeze handle database column defaults?

I can't find any info about this in the documentation, so I will ask here. How does breeze handle database column defaults? I have required columns in my database, but there are also default static values supplied for these in the database column definitions. Normally, I can insert null into these columns, and the new records will get the default. However, breeze doesn't seem to be aware of database column defaults, and the entities that have null in these columns fail validation on saving.
Thanks,
Mathias
Try editing the edmx xml by adding StoreGeneratedPattern = "Computed" attribute to the column with default value in the DB.
Edit:
Actually, before doing editing the xml, try setting the StoreGeneratedPattern property to Computed in the model editor itself.
Update:
This was fixed in Breeze 1.4.6 ( or later), available now.
Original Post:
There is currently in a bug in Breeze that should be fixed in the next release, out in about week. When this fix gets in then breeze will honor any defaultValues it finds in the EntityFramework data model.
One problem though is while it is easy to get 'defaultValues' into a Model First Entity Framework model via the properties editor, it's actually difficult to get it into a Code First EF model, unless you use fluent configuration. Unfortunately, EF ignores the [DefaultValue] attribute when constructing Code First model metadata.
One workaround that you can use now is to poke the 'defaultValue' directly onto any dataProperty. Something like:
var customerType = myEntityManager.metadataStore.getEntityType("Customer");
var fooProperty = customerType.getProperty("foo");
fooProperty.defaultValue = 123;

UpdateModel() cannot assign new value to navigation property (entity reference)

This happens in ASP.NET MVC 2, .NET 4 (EF 4). My Address entity has a reference to the Post reference. Zip is the primary key of the Post entity. Another property in Post entity is CityName. In my views I allow users to change the CityName for the address which automatically (via jquery) loads up the corresponding Zip and stores it inside a hidden field.
When posted, both values are posted fine and binded to the Address's Post reference. But UpdateModel() fails to update them. It says that the Zip is part of the entity's Entity Key and cannot be changed.
I would gladly load up the Post entity by the new Zip and manually assign it to the existing Address but for all other properties I stall want to rely on UpdateModel().
How can I achieve that? One would think that in EF4 stuff like this has been resolved..
By default the entity framework generated classes put restrictions on changing primary key values. This is good. You shouldn't change a PK for any reason at all. Changing PKs outside of add scenarios has pretty huge ramifications for state tracking and the general health of your system.
To solve this problem you want to tell UpdateModel not to update your primary keys using the exclude parameter.

Resources