我所有的实体都继承自IValidatableObject。我遇到的问题是,当我保存一个实体并且该实体包含一个引用另一个未完全加载的实体的属性(它不为空,但仅包含内部带有引用键的对象)时,代码会引发错误。错误是属性(引用另一个实体)未正确验证。这是真的,因为对象只包含 ID。让我用一个小例子告诉你我在说什么:
public class Exercise : BaseModel
{
public LocalizedString Name { get; set; }
public virtual Muscle Muscle { get; set; }
public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Name == null)
{
yield return new ValidationResult("Name is mandatory", new[] { "Name" });
yield break;
}
if (Name.French == null || Name.French.Length < 3)
{
yield return new ValidationResult("Exercise's French name must be over 3 characters");
}
if (Name.English == null || Name.English.Length < 3)
{
yield return new ValidationResult("Exercise's English name must be over 3 characters");
}
if (Muscle == null)
{
yield return new ValidationResult("Exercice must be assigned to a muscle");
}
}
}
public class Muscle : BaseModel
{
public LocalizedString Name { get; set; }
public ICollection<Exercise> Exercises { get; set; }
public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Name == null)
{
yield return new ValidationResult("Name is mandatory", new[] { "Name" });
yield break;
}
if (Name.French == null || Name.French.Length < 3)
{
yield return new ValidationResult("Muscle's French name must be over 3 characters");
}
if (Name.English == null || Name.English.Length < 3)
{
yield return new ValidationResult("Muscle's English name must be over 3 characters");
}
}
}
//--- This is the code into the repository:
public int Insert(Exercise entity)
{
if (entity.Muscle != null)
{
var localExercise = DatabaseContext.Set<Muscle>().Local.SingleOrDefault(e => e.Id == entity.Muscle.Id);
if (localExercise != null)
{
DatabaseContext.Set<Muscle>().Attach(entity.Muscle);
}
}
DatabaseContext.Set<Exercise>().Add(entity);
return DatabaseContext.SaveChanges();
}
我正在保存练习。练习包含一个名称,而 Muscle 设置了一个有效的 ID,但不包含任何名称。这就是为什么当我保存时在实体框架内进行验证,告诉我肌肉对象需要名称。
我不需要完全加载肌肉,因为我只想附上这个。我不想在练习里面有一个属性“MuscleID”。我真的很想拥有这种结构。
谁能告诉我我需要做什么才能让验证只发生在保存的实体上而不是外来对象上?