BreezeJS和Hottowel的日期无效

时间:2013-06-07 13:39:33

标签: entity-framework breeze durandal hottowel

我有一个问题,whit breeze返回DateTime ...我也尝试将BreezeJs更新到最新版本,但没有任何改变。我使用breezeJs和HotTowel SPA

控制器:

[BreezeController]
public class ContribuentiController : ApiController
{
    readonly EFContextProvider<LarksTribContext> _contextProvider =
    new EFContextProvider<LarksTribContext>();

    [System.Web.Http.HttpGet]
    public string Metadata()
    {
        return _contextProvider.Metadata();
    }


    // ~/api/todos/Todos
    // ~/api/todos/Todos?$filter=IsArchived eq false&$orderby=CreatedAt 
    [System.Web.Http.HttpGet]
    public IQueryable<Contribuente> Contribuenti()
    {
        if (_contextProvider.Context.Contribuente != null)
        {
            return _contextProvider.Context.Contribuente.Include("Residenze.Strada");//.Include("Residenze").Include("Residenze.Strada");
        }
        else
        {
            return null;
        }
    }


    [System.Web.Http.HttpPost]
    public SaveResult SaveChanges(JObject saveBundle)
    {
        return _contextProvider.SaveChanges(saveBundle);
    }
}

型号:

[Table(name: "Contribuenti")]
public class Contribuente
{
    [Key]
    public int Id { get; set; }

    [MaxLength(30,ErrorMessage = "Il cognome non deve superare i 30 caratteri")]
    public string Cognome { get; set; }

    [MaxLength(35, ErrorMessage = "Il nome non deve superare i 35 caratteri")]
    public string Nome { get; set; }

    [MaxLength(16, ErrorMessage = "Il Codice fiscale non deve superare i 16 caratteri")]
    public string CodiceFiscale { get; set; }

    public virtual ICollection<Residenza> Residenze { get; set; }

}

[Table(name: "Residenze")]
public class Residenza
{
    [Key, Column(Order = 0)]
    public int Id { get; set; }



    public int ContribuenteId { get; set; }
    [ForeignKey("ContribuenteId")]   
    public Contribuente Contribuente { get; set; }


    public DateTime? DataInizio { get; set; }

    public int StradaId { get; set; }
    [ForeignKey("StradaId")]
    public Strada Strada { get; set; }

    public int Civico { get; set; }
    public string Interno { get; set; }
    public string Lettera { get; set; }


}

[Table(name: "Strade")]
public class Strada
{

    [Key]
    public int Id { get; set; }

    [MaxLength(20,ErrorMessage = "Il toponimo deve contenere al massimo 20 caratteri")]
    public string Toponimo { get; set; }

    [MaxLength(50, ErrorMessage = "Il nome deve contenere al massimo 50 caratteri")]
    public string Nome { get; set; }

}

当我进行此查询时:

var query = breeze.EntityQuery.
            from("Contribuenti").expand(["Residenze"], ["Strada"]);

json的回应是:

[{"$id":"1","$type":"LarksTribUnico.Models.Contribuente, LarksTribUnico","Id":1,"Cognome":"Manuele","Nome":"Pagliarani","CodiceFiscale":"HSDJSHDKHSD","Residenze":[{"$id":"2","$type":"LarksTribUnico.Models.Residenza, LarksTribUnico","Id":5,"ContribuenteId":1,"Contribuente":{"$ref":"1"},"DataInizio":"2012-12-10T22.00.00.000","StradaId":4,"Strada":{"$id":"3","$type":"LarksTribUnico.Models.Strada, LarksTribUnico","Id":4,"Toponimo":"Via","Nome":"Milano"},"Civico":0}]}]

但是在查询结果中“DataInizio”始终标记为“无效日期”。

知道这个问题吗? 感谢

1 个答案:

答案 0 :(得分:1)

Breeze服务器端将SQL Server DateTime转换为ISO 8601.在我的代码(breeze v0.72)中,日期似乎在SQL中以UTC结尾,并在微风中转换回本地。

查看日期上的Breeze文档。 http://www.breezejs.com/documentation/date-time

或者,正如breeze docs中所建议的那样,如果HotTowel没有,你可以将moment.js添加到你的项目中。 https://github.com/moment/moment

Moment会识别您正在描述的JSON。

moment()与JavaScript日期不同,但更容易操作和解析。 这个代码是您当前浏览器的日期。

var now = window.moment().toDate();

此代码演示了如何将ISO转换为JavaScript Date对象。

// ISO 8601 datetime returned in JSON.  
// In your code, you would pull it out of your the 
// return variable in your dataservice.js
var DataInizio = "2012-12-10T22.00.00.000" 

// convert your variable to a moment so you can parse it 
var momentdatainizio = window.moment(DataInizio); 

// convert the ISO to a javascript Date object so you can use it in js.
var mydate = window.moment(DataInizio).toDate();  

您的Stada将最终进入您用来填充viewModel的微风元数据存储区。

在dataservice.js中使用类似代码的方式从元数据存储或数据库中检索strada。我比需要的更冗长,所以你可以调试。

var getStrada  = function (stradaId, callback) {
    var query = EntityQuery.from("Strada")
        .using(manager);
    var pred = new breeze.Predicate("idd", "eq", stradaId);
    // create the query
    var queryb = query.where(pred);

    // check the MetadataStore to see if you already have it
    var localsession = queryb.executeLocally();
    if (localsession) {
        if (localsession.length > {          
           window.app.vm.strada.strada(data.results);
           return localsession;
        }
    }
    // get it from the server
    else {
        // return the promise to prevent blocking
        //  then set your viewModel when the query fulfills
        //  then make your callback if there is one
        //  handle the fail in your queryFailed function if there is a problem
        return manager.executeQuery(queryb)            
        .then(function (data) {
            window.app.vm.strada.strada(data.results);
        })
        .then(function () {
            if ((typeof callback !== 'undefined' && callback !== null)) {
                callback();
            }
        })
        .fail(function () {
            queryFailed();
        });
    }
};

这是strada.js中ko viewModel的片段

app.vm.strada = (function ($, ko, dataservice, router) {
    var strada = ko.observable();
    ...
    return {
         strada : strada,
         ...
 })($, ko, app.dataservice, app.router);

这是ko.bindingHandlers.js中knockout的自定义绑定处理程序。这段代码有点冗长,所以你可以调试中间变量。

window.ko.bindingHandlers.DataInizio = {
  // viewModel is a Strada
  update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
    var value = valueAccessor(), allBindings = allBindingsAccessor();
    var valueUnwrapped = window.ko.utils.unwrapObservable(value);
    var $el = $(element);
    if (valueUnwrapped.toString().indexOf('Jan 1') >= 0)
        $el.text("Strada not Started");
    else {
        var date = new Date(valueUnwrapped);
        var d = moment(date);
        $el.text(d.format('MM/DD/YYYY'));
    }
  }
};

这是绑定处理程序的html      ...              Strada DataInizio:               ...     

我使用Breeze v0.72编写了基于我的代码的代码,它使用sammy.js作为路由器。您的里程可能因微风和Durandel的新版本而异。