不能隐式转换类型在我的任务中。

huangapple go评论57阅读模式
英文:

Cannot implicitly convert type in my task

问题

我有一个DateTime属性我正在尝试设置。但是我收到一个错误消息,说

"无法隐式将类型'System.DateTime'转换为'ProjectName.Core.Entities.MyClassName'"

我如何将我的变量赋值回它的属性?

这是具有我试图设置的属性的类

public class MyClassName
{
   public DateTime? MyDateTime { get; set; }
}

这是我正在尝试将变量赋值回属性但收到上述消息的任务。我漏掉了什么?

public async Task<MyClassName> GetMyDateDateAsync()
 {
  var myVar = (from x in _dbDbContext.Table select x.Column).Max();          
     return myVar;
 }
英文:

I have a DateTime property I am trying to set. However I am receiving an error that says

"Cannot implicitly convert type 'System.DateTime' to 'ProjectName.Core.Entities.MyClassName'"

How do I assign my variable back to it's property?

Here is the class with the Property I am trying to set

public class MyClassName
{
   public DateTime? MyDateTime { get; set; }
}

Here is my task where I am trying to assign the variable back to the property but am receiving the above message. What am I missing?

public async Task&lt;MyClassName&gt; GetMyDateDateAsync()
 {
  var myVar = (from x in _dbDbContext.Table select x.Column).Max();          
     return myVar;
 }

答案1

得分: 2

你的myVar与返回的类型不匹配。

一种选择是只需创建一个实例:

public async Task<MyClassName> GetMyDateDateAsync()
{
    return new MyClassName
    {
        MyDateTime = await _dbDbContext.Table.MaxAsync(x => x.Column)
    };
}

如果_dbDbContext.Table存储了MyClassName,并且你想返回具有最大MyDateTime的实例,则尝试以下代码:

public async Task<MyClassName> GetMyDateDateAsync()
{
    return await _dbDbContext.Table
        .OrderByDescending(x => x.Column)
        .FirstAsync();
}
英文:

You have type mismatch between myVar and returned type.

One option would be to just create an instance:

public async Task&lt;MyClassName&gt; GetMyDateDateAsync()
{     
    return new MyClassName
    {
        MyDateTime = await  _dbDbContext.Table.MaxAsync(x =&gt; x.Column)
    };
}

If _dbDbContext.Table stores the MyClassName and you want to return one with max MyDateTime then try:

public async Task&lt;MyClassName&gt; GetMyDateDateAsync()
{
    return await _dbDbContext.Table
        .OrderByDescending(x =&gt; x.Column)
        .First();
}

huangapple
  • 本文由 发表于 2023年8月5日 02:44:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76838469.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定