How to serialize & deserialize TimeOnly in C# and MongoDB - c#

Iam using .NET 6 and TimeOnly? datatype in a C# model class. The database is MongoDB 4.4.
TimeOnly? (15:15 Hours) is saved into MongoDB as below.
"defaultTime" : {
"hour" : 15,
"minute" : 15,
"second" : 0,
"millisecond" : 0,
"ticks" : NumberLong(549000000000)
}
But when the data is read from MongoDB, Iam getting the following exception.
An unhandled exception has occurred while executing the request.
System.FormatException: An error occurred while deserializing the DefaultTime property of class Models.Customer: Value class System.TimeOnly cannot be deserialized.
---> MongoDB.Bson.BsonSerializationException: Value class System.TimeOnly cannot be deserialized.
at MongoDB.Bson.Serialization.BsonClassMapSerializer`1.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Deserialize[TValue](IBsonSerializer`1 serializer, BsonDeserializationContext context)
at MongoDB.Bson.Serialization.Serializers.NullableSerializer`1.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
at MongoDB.Bson.Serialization.Serializers.SerializerBase`1.MongoDB.Bson.Serialization.IBsonSerializer.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Deserialize(IBsonSerializer serializer, BsonDeserializationContext context)
at MongoDB.Bson.Serialization.BsonClassMapSerializer`1.DeserializeMemberValue(BsonDeserializationContext context, BsonMemberMap memberMap)
Any help on serialization and deserialization of TimeOnly datatype ?
Update:
I chose to save ticks in MongoDB to avoid the serialization & deserialization issues as below.
"defaultTime" : NumberLong(549000000000)

Related

Alexa Skill request deserialization fails - json to SkillRequest object C#

I would like to get some help here, I am using Alexa.NET nuget package to develop a custom alexa skill using c#, I get the following error.
My Request to the Function(AWS Lambda):
{
"version": "1.0",
"session": {
"new": true,
"sessionId": "amzn1.echo-api.session.[unique-value-here]",
"application": {
"applicationId": "amzn1.ask.skill.[unique-value-here]"
},
"user": {
"userId": "amzn1.ask.account.[unique-value-here]"
},
"attributes": {}
},
"context": {
"AudioPlayer": {
"playerActivity": "IDLE"
},
"System": {
"application": {
"applicationId": "amzn1.ask.skill.[unique-value-here]"
},
"user": {
"userId": "amzn1.ask.account.[unique-value-here]"
},
"device": {
"supportedInterfaces": {
"AudioPlayer": {}
}
}
}
},
"request": {
"type": "LaunchRequest",
"requestId": "amzn1.echo-api.request.[unique-value-here]",
"timestamp": "2016-10-27T18:21:44Z",
"locale": "en-US"
}
}
The Deserialization Error:
System.Exception: Error deserializing the input JSON to type SkillRequest
at Amazon.Lambda.TestTool.Runtime.LambdaExecutor.BuildParameters(ExecutionRequest request, ILambdaContext context) in C:\codebuild\tmp\output\src142363207\src\Tools\LambdaTestTool\src\Amazon.Lambda.TestTool\Runtime\LambdaExecutor.cs:line 214
at Amazon.Lambda.TestTool.Runtime.LambdaExecutor.ExecuteAsync(ExecutionRequest request) in C:\codebuild\tmp\output\src142363207\src\Tools\LambdaTestTool\src\Amazon.Lambda.TestTool\Runtime\LambdaExecutor.cs:line 52
---------------- Inner 1 Exception ------------
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Amazon.Lambda.TestTool.Runtime.LambdaExecutor.BuildParameters(ExecutionRequest request, ILambdaContext context) in C:\codebuild\tmp\output\src142363207\src\Tools\LambdaTestTool\src\Amazon.Lambda.TestTool\Runtime\LambdaExecutor.cs:line 202
---------------- Inner 2 Exception ------------
Amazon.Lambda.Serialization.SystemTextJson.JsonSerializerException: Error converting the Lambda event JSON payload to type Alexa.NET.Request.SkillRequest: Deserialization of reference types without parameterless constructor is not supported. Type 'Alexa.NET.Request.Type.Request'
at Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer.Deserialize[T](Stream requestStream)
---------------- Inner 3 Exception ------------
System.NotSupportedException: Deserialization of reference types without parameterless constructor is not supported. Type 'Alexa.NET.Request.Type.Request'
at System.Text.Json.ThrowHelper.ThrowNotSupportedException_DeserializeCreateObjectDelegateIsNull(Type invalidType)
at System.Text.Json.JsonSerializer.HandleStartObject(JsonSerializerOptions options, ReadStack& state)
at System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& readStack)
at System.Text.Json.JsonSerializer.ReadCore(Type returnType, JsonSerializerOptions options, Utf8JsonReader& reader)
at System.Text.Json.JsonSerializer.ParseCore(ReadOnlySpan`1 utf8Json, Type returnType, JsonSerializerOptions options)
at System.Text.Json.JsonSerializer.Deserialize[TValue](ReadOnlySpan`1 utf8Json, JsonSerializerOptions options)
at Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer.Deserialize[T](Stream requestStream)
SkillRequest.cs(From Alexa.NET nuget package):
public class SkillRequest
{
public SkillRequest();
[JsonProperty("version")]
public string Version { get; set; }
[JsonProperty("session")]
public Session Session { get; set; }
[JsonProperty("context")]
public Context Context { get; set; }
[JsonProperty("request")]
public Type.Request Request { get; set; } //This is throwing the deserialization error
//See below for properties within this.
public System.Type GetRequestType();
}
Request property type in SkillRequest above(this is where the problem is I think):
[JsonConverter(typeof(RequestConverter))]
public abstract class Request
{
protected Request();
[JsonProperty("type", Required = Required.Always)]
public string Type { get; set; }
[JsonProperty("requestId")]
public string RequestId { get; set; }
[JsonProperty("locale")]
public string Locale { get; set; }
[JsonConverter(typeof(MixedDateTimeConverter))]
[JsonProperty("timestamp")]
public DateTime Timestamp { get; set; } // This might be the problem?
}
I tried different DateTime formats, I played around by removing properties, to see if it goes past the deserialization error, nothing seems to be working. Can someone help?
I had this same issue, serializing JSON as per an Alexa tutorial I was following. This post helped me to resolve it, however, I was not comfortable with the idea of rewriting the Alexa.net class locally, as it was used this way in working tutorials I was following.
According to: Amazon From .net core 3 there is a new JSON serializer used in the templates. It provides a performance benefit, but also seems to introduce this error with Alexa.Net.
[assembly: LambdaSerializerAttribute(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
was replaced by
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
The new serializer was throwing the 'parameterless constructor' error. After installing the Amazon.Lambda.Serialization.Json package via Nuget, and referencing the previous version of the serializer referenced in the tutorials I was following, all worked perfectly.
Just wanted to chime in with what worked for me.
I have a ASP.NET Core 3.1 Web API service I'm hitting from Alexa and was getting this same error. I added a reference to NuGet package Microsoft.AspNetCore.Mvc.NewtonsoftJson and then popped this into my Startup.cs file: services.AddControllers().AddNewtonsoftJson(); in the ConfigureServices() function.
Source: https://dotnetcoretutorials.com/2019/12/19/using-newtonsoft-json-in-net-core-3-projects/
Also looks like this was sort of reported as an issue
https://github.com/timheuer/alexa-skills-dotnet/issues/193

Error occurred when trying to create a controller of type 'EmployeeController'. Make sure controller has a parameterless public constructor

Why I'm I getting this error on Employee Controller rest of them are working perfectly
Here is my Employee Controller
public class EmployeeController : ApiController
{
#region Call service
private readonly IEmployeeServices _employeeServices;
public EmployeeController(IEmployeeServices employeeServices)
{
_employeeServices = employeeServices;
}
readonly IEmployeeServices employeeServices = new EmployeeServices();
public EmployeeController():base()
{
_employeeServices = employeeServices;
}
}
AND this is my perfectly Working Product Controller
public class ProductController : ApiController
{
#region Call service
private readonly IProductServices _productServices;
public ProductController(IProductServices productServices)
{
_productServices = productServices;
}
readonly IProductServices productServices = new ProductServices();
public ProductController()
{
_productServices = productServices;
}
}
Here is the stack trace
An error has occurred.An error occurred when trying to create a controller of type 'EmployeeController'. Make sure that the controller has a parameterless public constructor.System.InvalidOperationException at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
 at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)
 at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()An error has occurred.Resolution of the dependency failed, type = "TheWork.Controllers.EmployeeController", name = "(none)".
 Exception occurred while: while resolving.
 Exception is: InvalidOperationException - The current type, BusinessServices.IEmployeeServices, is an interface and cannot be constructed. Are you missing a type mapping?
 -----------------------------------------------
 At the time of the exception, the container was:
 
 Resolving TheWork.Controllers.EmployeeController,(none)
 Resolving parameter "employeeServices" of constructor TheWork.Controllers.EmployeeController(BusinessServices.IEmployeeServices employeeServices)
 Resolving BusinessServices.IEmployeeServices,(none)
 Microsoft.Practices.Unity.ResolutionFailedException at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable1 resolverOverrides)
 at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides)
 at Microsoft.Practices.Unity.UnityContainerExtensions.Resolve(IUnityContainer container, Type t, ResolverOverride[] overrides)
 at Unity.WebApi.UnityDependencyScope.GetService(Type serviceType)
 at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func1& activator)
 at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)An error has occurred.The current type, BusinessServices.IEmployeeServices, is an interface and cannot be constructed. Are you missing a type mapping?System.InvalidOperationException at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForAttemptingToConstructInterface(IBuilderContext context)
 at lambda_method(Closure , IBuilderContext )
 at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)
 at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
 at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
 at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
 at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)
 at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)
 at lambda_method(Closure , IBuilderContext )
 at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)
 at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
 at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
 at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
 at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
Update
Here is the Unity Configuration
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
System.Web.Mvc.DependencyResolver.SetResolver(new UnityDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
RegisterTypes(container);
}
public static void RegisterTypes(IUnityContainer container)
{
ComponentLoader.LoadContainer(container, ".\\bin", "TheWork.dll");
ComponentLoader.LoadContainer(container, ".\\bin", "BusinessServices.dll");
ComponentLoader.LoadContainer(container, ".\\bin", "DataModel.dll");
}
}
Buried in the stack trace is the root cause of the issue:
InvalidOperationException - The current type,
BusinessServices.IEmployeeServices, is an interface and cannot be
constructed. Are you missing a type mapping?
----------------------------------------------- At the time of the exception, the container was: Resolving
TheWork.Controllers.EmployeeController,(none) Resolving parameter
"employeeServices" of constructor
TheWork.Controllers.EmployeeController(BusinessServices.IEmployeeServices
employeeServices) Resolving BusinessServices.IEmployeeServices,(none)
Microsoft.Practices.Unity.ResolutionFailedException at
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object
existing, String name, IEnumerable1 resolverOverrides)
The issue is that the EmployeeController requires an instance of IEmployeeServices but Unity does not know what concrete type to instantiate. It looks like the implementation class is supposed to be registered by the call to ComponentLoader.LoadContainer(container, ".\\bin", "BusinessServices.dll"); but for some reason it is not being registered. It could be a bug in that code or perhaps the BusinessServices.dll is out of date and does not contain the IEmployeeServices definition.
It's hard to tell why IEmployeeServices is not registered without seeing all the code and runtime dependencies (because types are being dynamically loaded/registered).
Try this way :)
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IEmployeeServices >().To<EmployeeServices >().InRequestScope();
}

NServiceBus System.ArgumentNullException

I'm new to NServiceBus (and a green developer) and I'm getting destroyed by this exception (in the NSB console, before calling the handler):
2014-02-26 14:27:10,269 [8] ERROR NServiceBus.Unicast.Transport.TransportReceiver [(null)] <(null)> -
Failed to deserialize message with ID: b0e459fa-0ada-431c-bbee-a2de00ee2a29
System.Runtime.Serialization.SerializationException: An error occurred while attempting to extract logical messages
from transport message NServiceBus.TransportMessage ---> System.ArgumentNullException: Value cannot be null.
Parameter name: path
at System.IO.Path.CheckInvalidPathChars(String path, Boolean checkAdditional)
at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionA
ccess access, AccessControlActions control, String[] pathListOrig, Boolean check
ForDuplicates, Boolean needFullPath, Boolean copyPathList)
at System.IO.FileSystemInfo.set_Attributes(FileAttributes value)
at SetIsReadOnly(Object , Object )
at NServiceBus.Serializers.XML.XmlMessageSerializer.GetObjectOfTypeFromNode(T
ype t, XmlNode node) in c:\BuildAgent\work\31f8c64a6e8a2d7c\src\NServiceBus.Core
\Serializers\XML\XmlMessageSerializer.cs:line 492
at NServiceBus.Serializers.XML.XmlMessageSerializer.GetPropertyValue(Type typ
e, XmlNode n) in c:\BuildAgent\work\31f8c64a6e8a2d7c\src\NServiceBus.Core\Serial
izers\XML\XmlMessageSerializer.cs:line 828
at NServiceBus.Serializers.XML.XmlMessageSerializer.GetObjectOfTypeFromNode(T
ype t, XmlNode node) in c:\BuildAgent\work\31f8c64a6e8a2d7c\src\NServiceBus.Core
\Serializers\XML\XmlMessageSerializer.cs:line 487
at NServiceBus.Serializers.XML.XmlMessageSerializer.Process(XmlNode node, Obj
ect parent, Type nodeType) in c:\BuildAgent\work\31f8c64a6e8a2d7c\src\NServiceBu
s.Core\Serializers\XML\XmlMessageSerializer.cs:line 379
at NServiceBus.Serializers.XML.XmlMessageSerializer.Deserialize(Stream stream
, IList`1 messageTypesToDeserialize) in c:\BuildAgent\work\31f8c64a6e8a2d7c\src\
NServiceBus.Core\Serializers\XML\XmlMessageSerializer.cs:line 359
at NServiceBus.Unicast.Messages.ExtractLogicalMessagesBehavior.Extract(Transp
ortMessage physicalMessage) in c:\BuildAgent\work\31f8c64a6e8a2d7c\src\NServiceB
us.Core\Unicast\Messages\ExtractLogicalMessagesBehavior.cs:line 74
at NServiceBus.Unicast.Messages.ExtractLogicalMessagesBehavior.Invoke(Receive
PhysicalMessageContext context, Action next) in c:\BuildAgent\work\31f8c64a6e8a2
d7c\src\NServiceBus.Core\Unicast\Messages\ExtractLogicalMessagesBehavior.cs:line
52
--- End of inner exception stack trace ---
I got the MVC Example project working from the free chapters, but I couldn't get the pubsub example to work because 'Host doesn't support hosting of multiple endpoints.'
I'm working in 3 projects in my broken solution, just trying to get a simple 1-node pub and 1-node sub going:
Core (NServiceBus.Interfaces 4.4.1 from NuGet, contains Events folder with IFileUploadedEvent.cs)
FileWatcherService (NServiceBus.Host 4.4.1 from NuGet)
FileMoverService (NServiceBus.Host 4.4.1 from NuGet)
Core\Events\IFileUploadedEvent.cs:
using NServiceBus;
using ...
namespace Core.Events
{ public interface IFileUploadedEvent : IEvent
{ Guid EventId { get; set; }
string Client { get; set; }
FileInfo FileName { get; set; }
}
}
FileWatcherService has default app.config, no mappings.
FileWatcherService.EndpointConfig.cs:
namespace FileWatcherService
{ using NServiceBus;
public class EndpointConfig : IConfigureThisEndpoint, AsA_Publisher {}
}
FileWatcherService.FileWatcher.cs:
using NServiceBus;
using Core.Events;
using ...
namespace FileWatcherService
{ public class FileWatcher : IWantToRunWhenBusStartsAndStops
{ public IBus Bus { get; set; }
public void Activate()
{ ... }
...Stalker, calls PublishFileUploaded
public void PublishFileUploaded(FileInfo fileName, string clientName)
{ Bus.Publish<IFileUploadedEvent>(evt =>
{ evt.EventId = Guid.NewGuid();
evt.Client = clientName;
evt.FileName = fileName;
});
} } }
the FileMoverService.App.config contains:
<UnicastBusConfig>
<MessageEndpointMappings>
<add Messages="Core" Endpoint="FileWatcherService" />
</MessageEndpointMappings>
</UnicastBusConfig>
In the NSB windows, I see
FileMover: Subscribing to Core.Events.IFileUploadedEvent
FileWatcher: Subscribing FileMoverService#ccc to message type Core.Events.IFileUploadedEvent
The FileMover class implements IHandleMessages, but the code never reaches that because NServiceBus throws the first error.
I tried running Init() in the EndpointConfig, but I still get the same error.
Help me Please! What am I doing wrong?
If you want to move files or other blobs using NServiceBus, look at using our "data bus" capabilities described here:
http://docs.particular.net/NServiceBus/attachments-databus-sample
Turns out you can't Deserialize a FileInfo object. So I'll have to approach the problem completely differently.

ServiceStack TypeInitializationException on Apphost.Start()

I am using ServiceStack in standalone mode. It is now giving a TypeInitialzationException when executing Apphost.Start().
At the time, I was working on implementing some custom filters, but removing the annotation from the only filtered DTO class did not solve the problem.
The stack trace does not show any of my classes involved, and the failing class is the JsvReader which I don't use explicitly.
How can prevent this problem?
Note: I just used nuget to update all packages, so this is current as of now, 3.9.43 for all ServiceStack components.
Exception Detail
System.TypeInitializationException occurred
HResult=-2146233036
Message=The type initializer for 'ServiceStack.Text.Jsv.JsvReader`1' threw an exception.
Source=ServiceStack.Text
TypeName=ServiceStack.Text.Jsv.JsvReader`1
StackTrace:
at ServiceStack.Text.Jsv.JsvReader`1.GetParseFn()
at ServiceStack.Text.Jsv.JsvReader.GetParseFn(Type type)
at ServiceStack.ServiceModel.Serialization.StringMapTypeDeserializer..ctor(Type type)
at ServiceStack.ServiceHost.RestPath..ctor(Type requestType, String path, String verbs, String summary, String notes)
at ServiceStack.ServiceHost.ServiceController.RegisterRestPaths(Type requestType)
at ServiceStack.ServiceHost.ServiceController.RegisterCommon(Type serviceType, Type requestType, Type responseType)
at ServiceStack.ServiceHost.ServiceController.RegisterNService(ITypeFactory serviceFactoryFn, Type serviceType)
at ServiceStack.ServiceHost.ServiceController.Register(ITypeFactory serviceFactoryFn)
at ServiceStack.ServiceHost.ServiceManager.Init()
at ServiceStack.WebHost.Endpoints.Support.HttpListenerBase.Init()
at ArdWebServer.Program.Main(String[] args)
InnerException: System.TypeInitializationException
HResult=-2146233036
Message=The type initializer for 'ServiceStack.Text.Common.DeserializeSpecializedCollections`2' threw an exception.
Source=ServiceStack.Text
TypeName=ServiceStack.Text.Common.DeserializeSpecializedCollections`2
StackTrace:
at ServiceStack.Text.Common.DeserializeSpecializedCollections`2.get_Parse()
at ServiceStack.Text.Common.JsReader`1.GetCoreParseFn[T]()
at ServiceStack.Text.Common.JsReader`1.GetParseFn[T]()
at ServiceStack.Text.Jsv.JsvReader`1..cctor()
InnerException: System.NullReferenceException
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=ServiceStack.Text
StackTrace:
at ServiceStack.Text.PlatformExtensions.GenericTypeArguments(Type type)
at ServiceStack.Text.Common.DeserializeSpecializedCollections`2.GetGenericEnumerableParseFn()
at ServiceStack.Text.Common.DeserializeSpecializedCollections`2.GetParseFn()
at ServiceStack.Text.Common.DeserializeSpecializedCollections`2..cctor()
InnerException:
My App host
public class AppHost : AppHostHttpListenerBase
{
public AppHost() : base("IAM Tools Service Stack Host", typeof (Tims.Global).Assembly)
{
CatchAllHandlers.Add(
(httpMethod, pathInfo, filePath) =>
Tims.Support.StaticFileHandler.Factory(
Params.Instance.HttpDataDir,
"/",
pathInfo
)
);
}
public override void Configure(Funq.Container container)
{
SetConfig(new EndpointHostConfig()
{
DebugMode = true,
WriteErrorsToResponse = true
});
}
}

Automapper value type to SqlType conversions

I'm setting up a mapping between some nice, light weight POCOs and some big fat heavy data aware objects that are part of a legacy architecture.
The data objects are using SqlTypes for their properties - so I've got Data.Role.Name as SqlString but Poco.Role.Name as string.
Automapper is set up as such:
Mapper.CreateMap<Role, Data.Role>()
.ForMember(dest => dest.Role_ID,
opt => opt.MapFrom(src=>src.ID));
On the attempt to map Mapper.Map(pocoRole, dataRole), the exception (scroll down) is thrown.
How can I cause Automapper to map from string to sqlstring gracefully?
AutoMapper.AutoMapperMappingException : Trying to map Poco.Role to Data.Role.
Using mapping configuration for Poco.Role to Data.Role
Exception of type 'AutoMapper.AutoMapperMappingException' was thrown.
----> AutoMapper.AutoMapperMappingException : Trying to map System.String to System.Data.SqlTypes.SqlString.
Using mapping configuration for Poco.Role to Data.Role
Destination property: Name
Exception of type 'AutoMapper.AutoMapperMappingException' was thrown.
----> AutoMapper.AutoMapperMappingException : Trying to map System.String to System.Data.SqlTypes.SqlString.
Using mapping configuration for Poco.Role to Data.Role
Destination property: Name
Exception of type 'AutoMapper.AutoMapperMappingException' was thrown.
----> AutoMapper.AutoMapperMappingException : Trying to map System.String to System.Data.SqlTypes.SqlString.
Using mapping configuration for Poco.Role to Data.Role
Destination property: Name
Missing type map configuration or unsupported mapping.
Exception of type 'AutoMapper.AutoMapperMappingException' was thrown.
at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context)
at AutoMapper.MappingEngine.Map(Object source, Object destination, Type sourceType, Type destinationType)
at AutoMapper.MappingEngine.Map(TSource source, TDestination destination)
at AutoMapper.Mapper.Map(TSource source, TDestination destination)
at Repository.RoleRepository.FindAll(IRole filter) in RoleRepository.cs: line 31
at Repository.ReaderRepositoryBase`1.Find(TEntity filter) in ReaderRepositoryBase.cs: line 30
at Test.RepositoryTests.GetRoleInternal() in RepositoryTests.cs: line 79
--AutoMapperMappingException
at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.MapPropertyValue(ResolutionContext context, IMappingEngineRunner mapper, Object mappedObject, PropertyMap propertyMap)
at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.Map(ResolutionContext context, IMappingEngineRunner mapper)
at AutoMapper.Mappers.TypeMapMapper.Map(ResolutionContext context, IMappingEngineRunner mapper)
at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context)
--AutoMapperMappingException
at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context)
at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.MapPropertyValue(ResolutionContext context, IMappingEngineRunner mapper, Object mappedObject, PropertyMap propertyMap)
--AutoMapperMappingException
at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context)
I think you could use type converters for that. Look at this article:
http://automapper.codeplex.com/wikipage?title=Custom%20Type%20Converters
For that member, you should have to do something like:
.ForMember(d => d.Name, opt => opt.MapFrom(s => new SqlString(s.Name));
Or you could use the ContructUsing method.
Mapper.CreateMap<String, SqlString>().ConstructUsing(s => new SqlString(s));
Taking this approach will convert all String, SqlString pairs using the constructor so you don't need specific .ForMember maps.

Categories