I'm trying to add an object to a navigation property of an entity but I keep getting this exception.
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'.
Adding entity
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;
}
My domain model
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>();
}
}
If I should remove the collection initialization and just try to add the object I will get a null reference exception.
System.NullReferenceException
Object reference not set to an instance of an object.
So my question is how are navigation properties initialized? I thought just having the virtual keyword did all of this. \\
UPDATE
This is present in the 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();
}
}
Try this:
modelBuilder.Entity<User>()
.HasMany(u => u.Devices)
.WithOptional(d => d.User)
.Map(c => c.MapKey("UserId"));
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.