in my controller action I'm trying to add new image to database. Image requires to be associated with the device, which is associated with the user.
So I have my entity classess:
public class Image
{
public int Id { get; set; }
public string Url { get; set; }
[Required]
public virtual Device { get; set; }
}
public class Device
{
public int Id { get; set; }
public string Name { get; set; }
[Required]
public virtual User { get; set; }
}
public class User
{
public int Id { get; set; }
public string Login{ get; set; }
public virtual ICollection<Device> Devices { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public virtual string Email{ get; set; }
}
Now when I'm trying to add new image like this:
var image = new Image();
image.Device = Db.DbSet<Device>().Find(1);
Db.DbSet<Image>().Add(image);
Db.DbSet<Image>().SaveChanges();
The thing is that when I use this Find to lad existing device (with user and all properties set right) I don't get the correctly filled User property in the Device. It's like the lazy loading did not work. There is an instance of an User object, but it's id is set to 0 and it have all other fields set to its default values.
I have all navigation properties set as virtual, also lazy loading works okay on my other entities so it's definitely not turned off or something.
The funny thing is that when I change my code and comparison like below before I add my image then it loads user and works fine:
if (AuthenticationHelper.CurrentUser != image.Device.User)
return null;
Exactly like it manage to load user in this very moment. If we change this comparison order, to following image.Device.User != AuthenticationHelper.CurrentUser it do not work any more.
Any ideas what's going on with this?
Deviceclass have a default constructor that instantiates theUserproperty? If yes, try if it works correctly without the instantiation.