类型的对象不能从类型的EntityReference的Value属性中设置或删除

本文关键字:类型 设置 删除 属性 EntityReference 对象 不能 Value | 更新日期: 2023-09-27 18:09:39

我试图添加一个对象到一个实体的导航属性,但我一直得到这个异常。

System.InvalidOperationException
An object of type 'System.Collections.ObjectModel.Collection`1[[WakeSocial.BusinessProcess.Core.Domain.UserDevice, WakeSocial.BusinessProcess.Core.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' cannot be set or removed from the Value property of an EntityReference of type 'WakeSocial.BusinessProcess.Core.Domain.UserDevice'.

添加实体

    UserDevice device = new UserDevice();
    device.DeviceType = type;
    device.DeviceId = deviceId;
    device.PushId = pushId;
    device.HasFrontFacingCamera = hasFrontCamera;
    user.Devices.Add(device);
    await UpdateUser(user);

  public async Task<User> UpdateUser(User user)
  {
      Context.Entry(user).State = EntityState.Modified;
      await uow.SaveChangesAsync();
      return user;
  }

我的域模型

public enum Gender
{
    Male = 0,
    Female = 1
}
public class User
{
    public Guid UserId { get; private set; }
    public string FacebookUserId { get; set; }
    public string FacebookAccessToken { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public Gender Gender { get; set; }
    public int TokenCount { get; set; }

    public virtual ICollection<UserDevice> Devices { get; set; }
    public virtual ICollection<Beat> OwnedBeats { get; set; }
    public User()
    {
        UserId = GuidComb.Generate();
        Devices = new Collection<UserDevice>();
    }
}

如果我应该删除集合初始化,只是尝试添加对象,我将得到一个空引用异常。

System.NullReferenceException
Object reference not set to an instance of an object.
我的问题是导航属性是如何初始化的?我以为只要有虚拟关键字就能做到这一切。'

这存在于DbContext

      //User
      modelBuilder.Entity<User>()
          .HasOptional(u => u.Devices)
          .WithMany()
          .WillCascadeOnDelete();

UserDevice

 public class UserDevice
{
    public Guid UserDeviceId {get;private set;}
    public DeviceType DeviceType { get; set; }
    public string DeviceId { get; set; }
    //local GSM/Apple Push Id
    public string PushId { get; set; }
    //RegistrationId from Azure Hubs
    public string HubId { get; set; }
    public bool HasFrontFacingCamera { get; set; }
    public UserDevice()
    {
        UserDeviceId = GuidComb.Generate();
    }
}

类型的对象不能从类型的EntityReference的Value属性中设置或删除

试试这个:

modelBuilder.Entity<User>()
          .HasMany(u => u.Devices)
          .WithOptional(d => d.User) 
          .Map(c => c.MapKey("UserId"));