【问题标题】:How to generate DateTime using RestfulAPI Entity Framework DatabaseFirst如何首先使用 Restful API 实体框架数据库生成 DateTime
【发布时间】:2017-08-22 05:09:06
【问题描述】:

我正在尝试基于通过 Fiddler 发布 json 数据来生成当前 DateTime 这是我的帖子数据

{"Username":"Johnny","Message":"say hello"}

我的模特

 public partial class User
    {
        public int Id { get; set; }
        public string Username { get; set; }
        public string Message { get; set; }
        public System.DateTime DateCreated { get; set; }
    }

我的控制器

public void Post([FromBody] User user)
        {
            using (UserDataEntities entities = new UserDataEntities())
            {

                user.DateCreated = DateTime.Now;
                entities.Users.Add(user);
                entities.SaveChanges();
            }
        }

如何为我的模型自动生成 DateTime 以获取当前的 DateTime?

我遇到了异常

OptimisticConcurrencyException:存储更新、插入或删除语句影响了意外数量的行 (0)。自加载实体后,实体可能已被修改或删除。

【问题讨论】:

    标签: c# entity-framework api datetime asp.net-web-api


    【解决方案1】:

    选项 1:

    鉴于您使用的是 C# 6.0,您可以使用名为 auto-implemented property initializer 的酷炫新功能并这样做:

    public System.DateTime DateCreated { get; set; } = Datetime.Now
    

    选项 2:

    在您的模型中添加一个构造函数并在其中设置DateCreated 属性。像这样:

    public User() 
    {
        DateCreated = DateTime.Now;
    }
    

    【讨论】:

    • 它不起作用我仍然得到同样的异常,它只在我从 json 文件中发布参数 DateCreated 时起作用,例如 {"Username":"Johnny","Message":"say hello" "创建日期":"2017-08-14T00:00:00"}
    • 请您发布异常堆栈!我认为问题与日期生成无关......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-03
    • 2011-09-09
    相关资源
    最近更新 更多