DataMember注释StringLength似乎被忽略了。我收到格式错误的项目,将其转换为数据库对象,并在我试图保存他时收到错误。
在以下WCF WebService中,CompanyName设置为200 char max,属性为/p:AllowUnsafeBlocks=true
。
[StringLength(200)]
在此测试中,我发送了一个350 char CompanyName。
[ServiceContract]
public interface IDataExchanger
{
[OperationContract]
bool SetCustomer(Customer customer);
// [...]
}
[DataContract]
public class Customer
{
[DataMember(IsRequired = true)]
public RequestHeader Header;
[DataMember(IsRequired = true)]
[StringLength(20)]
public string ExternalId;
[DataMember(IsRequired = true)]
[StringLength(200)]
public string CompanyName;
// [...]
}
并收到此错误:
<soapenv:Body>
<tem:SetCustomer>
<!--Optional:-->
<tem:customer>
<wcf:CompanyName>13245678901324567890132456789013245678901324567890132456789013245678901324567890132456789013245678901324567890132456789013245678901324567890132456789013245678901324567890132456789013245678901324567890132456789013245678901324567890132456789013245678901324567890132456789013245678901324567890132456789013245678901324567890132456789013245678901324567890</wcf:CompanyName>
<wcf:ExternalId>132456</wcf:ExternalId>
<wcf:Header></wcf:Header>
</tem:customer>
</tem:SetCustomer>
Db实体符合要求:
System.Data.Entity.Validation.DbEntityValidationException : 'Validation failed for one or more entities.
See 'EntityValidationErrors' property for more details.'
à System.Data.Entity.Internal.InternalContext.SaveChanges()
à FooBar.Bdd.Repository`1.Save() dans Repository.cs:ligne 58
à FooBar.Service.DataExchanger.SetCustomer(Customer customer) dans DataExchangerWCF.cs:ligne 60
à SyncInvokeSetCustomer(Object , Object[] , Object[] )
à System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
à System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
基于此So answer,我尝试使用此方法来验证对象。 使用:
public class CustomerDlo
{
[Key]
public int Id { get; set; }
[MaxLength(20)]
public string ExternalId { get; set; }
[MaxLength(200)]
public string CompanyName { get; set; }
// [...]
}
在:
var vc = new ValidationContext(myObject, null, null);
var valid = Validator.TryValidateObject(myObject, vc, null, true);
我遇到了以下问题: