Upgrading from Entity Framework 4 to 5 resulted in error - entity-framework

After upgrading to EF 5 I keep getting Validation failed for one or more entities. See 'EntityValidationErrors' property for more details' in a particular instance of my code.
It turns out I have a field that is a NVARCHAR nullable in the database and it marked has [Required] with Data annotation in a partial class. The field in question is set to null programmatically. This worked fine in EF4 as it was validated against the database model (NVARCHAR nullable).
I need to keep that field marked as [Required] because it also takes user inputs in other instances.
What are my options? Can I ignore that attribute/validation error right before SaveChanges()?

This is why it is strongly recommended that you use View models, rather than passing your entities directly to the view. Your view and data model have different requirements, and trying to use the same model with validation causes problems.
Instead, remove the required attribute from your data model and create a View model that has the required on it, then use something like AutoMapper to map between them.

Related

Entity Framework Core can't map official types to PostgreSQL columns

I downloaded a sample database for Postgres (v14) (dvdrental) so I could follow some SQL tutorials. I wanted to create an ASP.NET Core (5) Web API for that database, so using scaffolding, I created the entities based on the database tables and columns, then after some minor changes, I wanted to create a new migration.
That step failed though, as I'm getting two errors (so far) regarding the data types.
The property 'Film.Fulltext' is of type 'NpgsqlTsVector' which is not supported by the current database provider. Either change the property CLR type or ignore the property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'
I tried to use [NotMapped], but got the same error. I also tried to specify
[Column(Typename = "tsvector")]
which is the official type mapping according to https://www.npgsql.org/doc/types/basic.html, but for some reason, EF core seems to ignore it completely and gives the same error.
The property 'Film.SpecialFeatures' could not be mapped because it is of type 'string[]', which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'
Which is, again, weird, as the Postgres websites says
public string[] Tags { get; set; }
The provider will create text[] columns for the above property..
So basically EF Core throws errors about something that is the officially recommended way of doing it, so I have no idea why these errors even occur or how I could solve them.
Any help is appreciated.
Thanks

Validation in a Doctrine entity where that property itself is an Entity derived from another entity using constraints

First of all I hope this question is allowed because I guess its a rather framework-specific question (Symfony). I am running into the following problem:
A form is submitted and checked for validity for creating a new 'Toernooionderdeel' and as a result the Persist and Flush operations of Doctrine for this Entity are to be called attempting to put the newly created entity into the database. Fairly basic stuff to this point. But the form fails at ->isValid() before persisting and flushing can commence.
In my case the Constraints are applied on properties in various ways through annotation.
#Assert\Valid specifically is used on properties that define ManyToOne relationships with other entities and it all works fine, until...
I attempt to use #Assert\Valid on a property of 'Toernooionderdeel' called '$toernooi' which represents a ManyToOne relationship (Toernooionderdeel -> Toernooi).
The difference between this one and the other relationships I validate in the same way is that this 'Toernooi' Entity is derived from another entity, where the other entities aren't.
Despite obviously having a 'Toernooi' defined under the '$toernooi' property of 'Toernooionderdeel', the Constraint detects it as a violation and thus the form doesnt pass validation.
What things do i have to consider when doing this type of validation (using Constraints) on an 'advanced' entity construction like this? Has any of you done this before and if so, how did you do it?
When the entity referenced in a property ("child") is validated in the parent object via Assert\Valid, it's validity is also checked. When the child entity isn't valid, the parent isn't valid either (transitive).

MVC4 EF Foreign Key Association causes invalid ModelState

Using EF with MVC4 allows you to specify the inclusion of Foreign Key columns in the model. While this not normally part of OR modeling, it does allow MVC4 to automatically generate views with dropdown lists, for the foreign key relationships, when you generate a controller with the MVC controller with read/write actions and views, using Entity Framework option.
I have hit a problem creating an object in this scenario.
Greatly simplified, the models in question are:
Questionnaire:
QuestionnaireID: PK
CandidateId: FK
Candidate: Associated object
Candidate:
CandidateID: PK
Name: string
The problem I have hit is that on a Create view post-back to create a new Questionnaire ModelState.IsValid is false. On investigation the error listed is The parameter conversion from type 'System.String' to type 'Data.Candidate' failed because no type converter can convert between these types.
ModelState.Keys includes Questionnaire.Candidate as well as Questionnaire.CandidateId (which is valid).
I am sure this is something simple, but would like to hear some solutions. The viewbag only has a set for the drop-down list and the view has an #model of type #model Data.Questionnaire. There are no editor fields bound to Questionnaire.Candidate..
As I have no idea why the built-in EF models do not like the MVC generated scaffolding, for Create postbacks with foreign key columns enabled, I have reverted to what is a more secure solution (still happy to hear why it fails out-of-the-box):
Create individual view models for specific sensitive operations like create
The theory goes that there are a number of problems using EF domain entities as viewmodels including:
They potentially expose too much information or allow additional fields to be posted back
Validation text is an interface concern and should not be part of a the data model (they actually suggest even the viewmodel is not the place for this text, but I digress).
So basically I now have a CreateCandidateQuestionnaireVM class with only the required fields for selecting appropriate values for a new instance.

Get values in NotMapped property in model class Entity Framwork Code First using linq

I have the below scenario. I am using EF 5 Code first, MVC 4 on VS 2010. I am using the Unit of Work and Repository pattern for my project.
I am not sure if this is possible or not. Kindly suggest.
I have a model class representing a database table. In the model class, I have a property that is decorated as [NotMapped]. I have a Stored Proc that returns data, similar to the model class. However, when I get the data in a List from the SP, it does not contain value for the [NotMapped] column (SP returns data for the [NotMapped] column though). This may be logically correct with respect to EF.
All I want to know is, do we have a way to get data populated for the [NotMapped] column. I want to achieve, CRUD using LINQ (excluding R - Read).
I would recommend to create a separate complex type for the stored procedure results. Otherwise sooner or later you will find yourself writing code to distinguish between entities coming from the DbSet or from the stored procedure. When the come from the stored procedure they can't be used in joins, for example. Or checks whether or not the unmapped property is set.
A very dirty approach could be to have two different contexts. With code first it is possible to have different contexts with different mappings to the same types, with and without the column ignored (if you use fluent mapping, not with data annotations). But that only succeeds if you tell EF not to check the database schema, so using migrations is ruled out as well. I would not do it!! For the same reason as I mentioned above. I would hate to have a type with a property that sometimes is and sometimes isn't set.

getting Entity Framework raw query to respect attributes

I'm using EF4, code first. As such, my model classes have a mix of public properties, some virtual properties (for lazy loaded data from other tables) and some properties that are affixed with [NotMapped] attributes so that they are skipped by EF.
Sometimes I like to make use of the raw query : c.Database.SqlQuery<T>("select ...") to use EF as a row mapper.
I noticed in Intellitrace that these queries were generating a lot of thrown and caught exceptions for "IndexOutOfRange". After some looking, the exceptions are all for the virtual and [NotMapped] properties on the model object. I don't want to have to construct a new data model class or parent class with just the table properties in it; is there some configuration step I've missed to tell the row mapper in the raw query runner to pay attention to the same annotations that the rest of EF uses? Maybe they fixed this in EF5?
If you execute dbContext.Database.SqlQuery EF will never use mapping. It will use just simple match of property names and columns in result set. Try to use dbSet.SqlQuery instead. It should reflect mapping because it can load data as attached entities.