[英]How to cast a model of T type to 'System.Dynamic.ExpandoObject' in C#?
I am trying to add some parameters in the class Job.cs我正在尝试在 class Job.cs中添加一些参数
namespace Test
{
public class Job
{
public int Id { get; set; }
public int JobId { get; set; }
public int JobPropertyType { get; set; }
public string JobValue { get; set; }
}
}
I am using Dapper for Inserting Data in the tables.我正在使用 Dapper 在表中插入数据。 Repository.cs
存储库.cs
public async Task<T> Add(T entity)
{
using (var connection = await _connectionFactory.GetConnectionAsync())
{
return await connection.InsertAsync<T>(entity);
}
}
I have used DapperMapper for mapping table and data.我使用 DapperMapper 来映射表和数据。 Mapper.cs
映射器.cs
public class JobMapper: ClassMapper<Job>
{
public JobMapper()
{
Schema("Job");
Table("Job");
Map(m => m.JobId).Column("JobId");
Map(m => m.JobPropertyType).Column("JobPropertyType");
Map(m => m.JobValue).Column("JobValue");
}
}
Here is the JobService.cs这是JobService.cs
public async Task<Job> InsertJob(int jobId, int jobPropertyType, string jobValue)
{
var job = new Job
{
JobId = jobId,
JobPropertyType = jobPropertyType,
JobValue = jobValue
};
return await this.Repository.Add(job);
}
Another service sending data另一个发送数据的服务
public async Task AddJob(int jobId, string snapshot)
{
if (!string.IsNullOrEmpty(snapshot))
{
await _jobService.InsertJob(jobId, (int)JobPropertiesEnum.Snapshot, snapshot);
}
When I am trying to Insert data here, I am getting this exception:当我尝试在此处插入数据时,出现此异常:
Message=Cannot implicitly convert type 'System.Dynamic.ExpandoObject' to 'Test.Job'. Message=无法将类型“System.Dynamic.ExpandoObject”隐式转换为“Test.Job”。 at the time of Inserting (InsertyAsync() in the Repository)
在插入时(存储库中的 InsertyAsync())
How can I cast it into Dynamic.ExpandoObject?如何将其转换为 Dynamic.ExpandoObject?
I assume you are using Dapper-Extensions from here: https://github.com/tmsmith/Dapper-Extensions/tree/master/DapperExtensions我假设您从这里使用 Dapper-Extensions: https://github.com/tmsmith/Dapper-Extensions/tree/master/DapperExtensions
InsertAsync returns a Task<dynamic>, dynamic is an ExpandoObject, so your problem arises when you try to get the return value. InsertAsync 返回一个Task<dynamic>,dynamic 是一个ExpandoObject,所以当你尝试获取返回值时就会出现问题。 The return value is the key of the inserted entity.
返回值是插入实体的键。
You can change your code to something like this (I ddn't have time to test it):您可以将代码更改为这样的(我没有时间测试它):
public async Task<T> Add(T entity)
{
using (var connection = await _connectionFactory.GetConnectionAsync())
{
var result = await connection.InsertAsync<T>(entity);
entity.Id = (int) result;
return Task.FromResult(entity);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.