2013-03-11 16 views
0

我们的数据库中有一个并发检查字段,它是一个SQL时间戳。有没有办法让Linq查询选择一个编码为Base64字符串的时间戳字段?

如果我使用与

@Html.HiddenFor(m => m.DatabaseRowVersion) 

剃刀视图它编码为Base64编码字符串,并结合回到我的模型在攒动的罚款。

如果我得到的场由JSON请求与

Json(queryable.Select(f => new { DatabaseRowVersion = f.DatabaseRowVersion })) 

然后将得到的JSON是一个8场字节数组,我不能让它绑定回到我在保存动作模型。有什么办法可以让Linq实体在序列化之前选择字段作为Base64字符串?

我的解决方案是一个看起来很脏的JavaScript函数来将8个字段字节数组转换为Base64字符串,但这并不美观,我宁愿原始的Json请求返回已编码的字段。我试过的所有东西都给了我一个不受支持的Linq to Entities函数异常。我不想在内存中执行它,我想找到某种Entities.Functions风格的实现它在SQL服务器上发生。

另一种我不介意这样做的方式是,如果可以让jQuery以某种方式发布保存请求,将8字段字节数组绑定到模型中的字节[],但是我尝试过的所有内容都不会'工作。我已经在帖子中尝试了所有传统:true和contentType:“application/json; charset = utf-8”,但没有像在Ajax帖子中成功绑定数组的其他操作那样成功。它似乎不像其他数组那样工作,因为模型绑定器似乎期望Base64字符串而不是模型上byte []字段的字节数组。

回答

0

我不知道,如果你还在寻找一个答案,但我已经设法通过字节数组转换成字符串来解决这个和背部:

string stringValue = System.Convert.ToBase64String(byteSource); 
Byte[] byteValue = System.Convert.FromBase64String(stringSource); 

对于你的情况,你可以创建一个ViewModel并使用AutoMapper来映射您的Model(具有Byte Array TimeStamp)和ViewModel(它们将具有String TimeStamp)。

最后,您将使用ViewModel创建视图,并在更新时将您的ViewModel映射回您的模型并从那里更新。这样你的隐藏字段将是一个字符串,你不会有现在的问题。

Automapper没有字节数组字符串之间的隐式转换方法,所以你必须实行这样的事情对你的转换器:

public class ByteArrayTypeConverter : ITypeConverter<string, Byte[]> 
    { 
     public Byte[] Convert(ResolutionContext context) 
     { 
      string source = (string)context.SourceValue; 
      if (source == null) 
      { 
       source = ""; 
      } 

      Byte[] returnValue = System.Convert.FromBase64String(source); 

      return returnValue; 
     } 
    } 

    public class StringTypeConverter : ITypeConverter<Byte[], string> 
    { 
     public string Convert(ResolutionContext context) 
     { 
      Byte[] source = (Byte[])context.SourceValue; 

      string returnValue = System.Convert.ToBase64String(source); 

      return returnValue; 
     } 
    } 

你的映射初始化会是这个样子:

Mapper.CreateMap<string, Byte[]>().ConvertUsing(new ByteArrayTypeConverter()); 
Mapper.CreateMap<Byte[], string>().ConvertUsing(new StringTypeConverter()); 
Mapper.CreateMap<YourViewModel, YourModel); 
Mapper.CreateMap<YourModel, YourViewModel>(); 

希望这会有所帮助。

相关问题