简体   繁体   中英

The property on entity type cannot be used for objects of type Nullable1 with Entity Framework

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;
            };
        }
    }

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;
                };
            }

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