Home > front end >  The property on entity type cannot be used for objects of type Nullable1 with Entity Framework
The property on entity type cannot be used for objects of type Nullable1 with Entity Framework

Time:12-07

The line dataContext.Entry(this).Property(property).IsModified = true; is causing this error below. This doesn't happen with non foreign key properties. Any clue why?

The property 'RankingId' on entity type 'TeamOrganizationSeason' cannot be used for objects of type Nullable1 because it is a property for objects of type Nullable1.

    public class TeamOrganizationSeason 
    {
        public int? RankingId { get; set; }

        [ForeignKey("RankingId")]
        public Ranking Ranking { get; set; }

        public void IsUpdated(TeamOrganizationSeason teamOrganizationSeason, DataContext dataContext)
        {
            Update(RankingId, teamOrganizationSeason.RankingId, dataContext, t => t.RankingId);
        }

        private void Update(double? current, double? original, DataContext dataContext, Expression<Func<TeamOrganizationSeason, double?>> property)
        {
            if (current != original)
            {
                var state = dataContext.Entry(this).State;
                dataContext.TeamOrganizationSeasons.Attach(this);
                dataContext.Entry(this).Property(property).IsModified = true;
            };
        }
    }

CodePudding user response:

This had to do not with nullable issues but with different types. An int being sent instead of a double was causing this error. So we made it generic and all is well.

Causing Code Error

if (!requestedType.IsAssignableFrom(propertyType))
            {
                throw Error.DbEntityEntry_WrongGenericForProp(
                    propertyName, declaringType.Name, requestedType.Name, propertyType.Name);
            }

Generic

  private void Update<T>(double? current, double? original, DataContext dataContext, Expression<Func<TeamOrganizationSeason, T>> property)
            {
                if (current != original)
                {
                    if (dataContext.Entry(this).State == EntityState.Detached)
                    {
                        dataContext.TeamOrganizationSeasons.Attach(this);
                    }
                    dataContext.Entry(this).Property(property).IsModified = true;
                };
            }
  • Related