简体   繁体   中英

ef6 include() for nullable properties with required attribute

We've just updated to the EF6 and have an issue with a strange behavior comparing to the previous version.

EF used to generate LEFT JOINs for the Include statement if the property was nullable. However it looks like this version takes into account also the [required] attribute.

For example I have the following class:

public class Client
{    
    [DisplayName("Industry Code")]
    [Required]
    public int? IndustryId { get; set; }

    [ForeignKey("IndustryId")]
    public Industry IndustryEntity { get; set; }
}

When we do

return db.Clients
    .Include(o => o.CountryISOEntity)
        .... 
    .Include(o => o.IndustryEntity)
    .Single(o => o.Id == clientId);

the previous version generated LEFT OUTER JOIN, but the new one generates INNER JOIN.

If I remove the [required] attribute than it generates the LEFT JOIN. But it's not an option in my case as we use this attribute to show the errors to the user, however the user has an option to save the incomplete entity and to return to it later. And when the user comes back it get an error that the record doesn't exist as the include generates INNER JOIN.

Is there a setting in the new EF6 to disable this behavior (to ignore the attributes) and to generate sql query based on the nullable information? Or can I force the LEFT JOIN in the include? Or is our only option to rollback to the previous EF version?

PS: we are using .Net 4.0

Thanks

I assume you want to use the Required attribute for form validation in MVC, not to tell Entity Framework that the property is required. This is why you need view models, so you can separate validation logic of views from Entity Framework validation logic.

Your view models represents a view and contains all the data that is needed to render the view. A domain model (entity) represents one (or more) table(s) in the database. View models don't necessarily contain the same properties as the domain model. In my personal experience they are usually a combination of different domain models.

If you create a view model for a Client , you can remove the validation attributes from your EF POCO.

The view model will look like this:

public class ClientModel
{
    [DisplayName("Industry Code")]
    [Required]
    public int IndustryId { get; set; }

    // Other properties..
}

Then your POCO can look like this:

public class Client
{
    public int? IndustryId { get; set; }

    [ForeignKey("IndustryId")]
    public Industry IndustryEntity { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM