英文:
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<MyClassName> 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<MyClassName> GetMyDateDateAsync()
{
return new MyClassName
{
MyDateTime = await _dbDbContext.Table.MaxAsync(x => x.Column)
};
}
If _dbDbContext.Table
stores the MyClassName
and you want to return one with max MyDateTime
then try:
public async Task<MyClassName> GetMyDateDateAsync()
{
return await _dbDbContext.Table
.OrderByDescending(x => x.Column)
.First();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论