我有一个实现 IValidatableObject 的 POCO 对象。
public class Documentation : IValidatableObject
{
[Key]
public int DocumentationId { get; set; }
[ForeignKey("Project")]
public int ProjectId { get; set; }
public virtual Project Project { get; set; }
public string FileGuid { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
return new[] { new ValidationResult("File has not been uploaded", new[] { "FileGuid" }) };
}
}
为什么 DbContext 会运行验证而 DbDomainService 不会?
此测试通过了 DbContext:
[TestMethod, ExpectedException(typeof(DbEntityValidationException))]
public void TestDbContext()
{
SampleDbContext ctx = new SampleDbContext();
var p = new Project()
{
ProjectName = "UnitTest",
};
var d = new Documentation()
{
FileGuid = "UnitTestDoc",
};
p.Documentations = new List<Documentation>();
p.Documentations.Add(d);
ctx.Projects.Add(p);
ctx.SaveChanges();
}
虽然这没有(没有抛出异常):
[TestMethod, ExpectedException(typeof(ValidationException))]
public void TestDbDomain()
{
SampleDomainService svc = new SampleDomainService();
svc.Initialize(ServiceProvider.CreateDomainServiceContext());
var p = new Project()
{
ProjectName = "UnitTest",
};
var d = new Documentation()
{
FileGuid = "UnitTestDoc",
Project = p,
};
ChangeSet changeSet = new ChangeSet(
new [] {
new ChangeSetEntry(1, p, null, DomainOperation.Insert),
new ChangeSetEntry(2, d, null, DomainOperation.Insert),
}
);
svc.Submit(changeSet);
}
示例代码在这里