entity-framework – 使用OData v4,EF6和Web API v2.2处理日期

前端之家收集整理的这篇文章主要介绍了entity-framework – 使用OData v4,EF6和Web API v2.2处理日期前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在从v1-3升级到v4,但我遇到了一些问题.

我的理解是DateTime不受支持,我必须始终使用DateTimeOffset.精细.

但在我在DateTime中存储sql日期数据类型之前,现在看来我得到了这个错误

Member Mapping specified is not valid. The type 'Edm.DateTimeOffset[Nullable=False,DefaultValue=,Precision=]' of member 'CreatedDate' in type 'MyEntity' is not compatible with 'sqlServer.date[Nullable=False,Precision=0]'

为此做了什么工作?我需要能够专门存储数据库中的日期(时间和地点并不重要).如果我能得到Edm.Date以及返回的数据类型会很棒,但我之前没有.

谢谢.

编辑:示例类

之前:

public class Ticket
{
    [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [required,MaxLength(50)]
    public string Reference { get; set; }

    [Column(TypeName = "date")]
    public DateTime LoggedDate { get; set; }
}

后:

public class Ticket
{
    [Key,MaxLength(50)]
    public string Reference { get; set; }

    [Column(TypeName = "date")]
    public DateTimeOffset LoggedDate { get; set; }
}

这在EF中无效.

解决方法

一种选择是在实体中定义新属性.说标题映射到EF:
public partial class Title
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Nullable<System.DateTime> CreatedOn { get; set; }
}

然后添加DateTimeOffset的新属性

public partial class Title
{
    [NotMapped]
    public DateTimeOffset? EdmCreatedOn
    {
        // Assume the CreateOn property stores UTC time.
        get
        {
            return CreatedOn.HasValue ? new DateTimeOffset(CreatedOn.Value,TimeSpan.FromHours(0)) : (DateTimeOffset?)null;
        }
        set
        {
            CreatedOn = value.HasValue ? value.Value.UtcDateTime : (DateTime?)null;
        }
    }
}

并且生成OData模型的代码如下所示:

public static IEdmModel GetModel()
    {
        ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
        EntityTypeConfiguration<Title> titleType= builder.EntityType<Title>();
        titleType.Ignore(t => t.CreatedOn);
        titleType.Property(t => t.EdmCreatedOn).Name = "CreatedOn";

        builder.EntitySet<Title>("Titles");

        builder.Namespace = typeof(Title).Namespace;

        return builder.GetEdmModel();
    }
}

控制器看起来像:

public class TitlesController : ODataController
{
    CustomerManagementSystemEntities entities = new CustomerManagementSystemEntities();

    [EnableQuery(PageSize = 10,MaxExpansionDepth = 5)]
    public IHttpActionResult Get()
    {
        IQueryable<Title> titles = entities.Titles;
        return Ok(titles);
    }

    public IHttpActionResult Post(Title title)
    {
        entities.Titles.Add(title);
        return Created(title);
    }
}
原文链接:https://www.f2er.com/html/226278.html

猜你在找的HTML相关文章