我有两个表,User和UserPhoto,这些表用一对多关系表示。我想有一个UserRepository类,它具有AddUser/UpdateUser/DeleteUser方法,还有AddUserPhoto和DeleteUserPhoto,因为我想实现一些逻辑,我想实现添加和删除存储库层中包含的用户照片。EF仓库验证失败原因不明
在AddUserPhoto方法中,我从集合中检索User对象,添加照片,将set修改为true并返回验证结果。如下
public bool AddUserPhoto(DbUserPhoto photo, object userId)
{
try
{
var dbItem = Context.Users.Find(userId);
if (dbItem == null)
throw new Exception(string.Format("User id {0} not found"
, userId));
// Some logic around ordering of photos and only having
//one primary photo
if (photo.IsPrimary)
{
foreach (var p in dbItem.Photos)
{
p.IsPrimary = false;
p.DisplayOrder++;
}
photo.DisplayOrder = 1;
}
else
{
var maxDisplayOrder = dbItem.Photos
.Max(p => p.DisplayOrder);
photo.DisplayOrder = maxDisplayOrder + 1;
}
dbItem.Photos.Add(photo);
Context.Users.Attach(dbItem);
Context.Entry(dbItem).State = EntityState.Modified;
return Context.Entry(dbItem).GetValidationResult().IsValid;
}
catch (Exception ex)
{
if (ex.InnerException != null)
throw new DataRepositoryException(ex.InnerException.Message,
"UserDataRepository.InsertItem",
ex.InnerException);
throw new DataRepositoryException(ex.Message,
"UserDataRepository.InsertItem",
ex);
}
}
我遇到的问题是验证返回用户实体的IsValid = False。我已经检查过,并且一旦从数据库中检索到,从Find()操作返回的用户的IsValid = False,表示“位置字段是必需的”。
位置是User的属性,它是强制性的,并且引用另一个表,称为GeographicalLocation,因此用户的Location属性应该是有效的GeographicalLocation对象。
我已经检查使用手表和用户(当返回)肯定有一个有效的位置分配给位置属性,所以我很困惑,为什么它是失败的验证。
有什么想法?
编辑:下面
[Table("User")]
public class DbUser : IEntityComparable<DbUser>
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
[Required]
[MaxLength(80)]
public string FirstName { get; set; }
[Required]
[MaxLength(80)]
public string LastName { get; set; }
[Required]
[MaxLength(80)]
public string EmailAddress { get; set; }
[Required]
public DateTime DateOfBirth { get; set; }
[Required]
[MaxLength(1)]
public string Gender { get; set; }
[Required]
public virtual DbGeographicalArea Location { get; set; }
}
,你能否告诉了'User'类? – Colin
如果dbItem不包含GeographicalLocation对象,请将其包含并重试 –
添加用户类。多一点的调试似乎表明,如果我通过代码进行调试并打开用户变量并显示其中包含的Location对象,则可以运行代码并运行。我猜这是与延迟加载有关吗?如何在上面的User类中指定不延迟加载GeographicalArea对象? – NZJames