Entity object cannot be referenced by multiple instances of IEntityChangeTracker - c#-4.0

I am having below mentioned POCO classes.
public class AppointmentModel
{
public InvoiceDetail InvoiceDetails { get; set; }
public Invoice Invoice { get; set; }
}
public class InvoiceDetail
{
public Invoice Invoice { get; set; }
}
public class Invoice
{
public Invoice()
{
Id = Guid.NewGuid(); Created = DateTime.Now;
}
public Guid Id { get; set; }
public virtual Appointment Appointment { get; set; }
}
I have tried to add that model inside repository is as below.
public void Booking(AppointmentModel appointmentModel)
{
appointmentModel.InvoiceDetails.Invoice.LatestTotal = latestinvoiceTotal;
Catalog.Appointments.Add(appointmentModel.InvoiceDetails.Invoice.Appointment);
Catalog.SaveChanges();
}
It gives below mentioned error.
An entity object cannot be referenced by multiple instances of
IEntityChangeTracker
Stack Trace is as below.
at System.Data.Objects.ObjectContext.VerifyContextForAddOrAttach(IEntityWrapper wrappedEntity)
at System.Data.Objects.ObjectContext.AddSingleObject(EntitySet entitySet, IEntityWrapper wrappedEntity, String argumentName)
at System.Data.Objects.DataClasses.RelatedEnd.AddEntityToObjectStateManager(IEntityWrapper wrappedEntity, Boolean doAttach)
at System.Data.Objects.DataClasses.RelatedEnd.AddGraphToObjectStateManager(IEntityWrapper wrappedEntity, Boolean relationshipAlreadyExists, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.RelatedEnd.IncludeEntity(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.EntityReference`1.Include(Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.RelationshipManager.AddRelatedEntitiesToObjectStateManager(Boolean doAttach)
at System.Data.Objects.ObjectContext.AddObject(String entitySetName, Object entity)
at System.Data.Entity.Internal.Linq.InternalSet`1.<>c__DisplayClass5.<Add>b__4()
at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
at System.Data.Entity.DbSet`1.Add(TEntity entity)
at PawLoyalty.Data.PetBookings.Repositories.InvoiceRepository.Booking(AppointmentModel appointmentModel) in d:\PawLoyalty Module\New Booking Flow\NewBookingFlow\PawLoyalty\PawLoyalty.Data\PetBookings\Repositories\InvoiceRepository.cs:line 339
at PawLoyalty.Business.Invoices.InvoiceService.Booking(AppointmentModel appointmentModel) in d:\PawLoyalty Module\New Booking Flow\NewBookingFlow\PawLoyalty\PawLoyalty.Business\Invoices\InvoiceService.cs:line 38
at PawLoyalty.Business.BookingFacadeService.Booking(AppointmentModel appointmentModel) in d:\PawLoyalty Module\New Booking Flow\NewBookingFlow\PawLoyalty\PawLoyalty.Business\BookingFacadeService.cs:line 152
at PawLoyalty.Web.Controllers.PetBookingController.BookingProcess(String providerKey, String ownerKey, String serviceId, String petKeys, String selectedDates, String selectedExtraServices, String selectedResourceId, String key, String type) in d:\PawLoyalty Module\New Booking Flow\NewBookingFlow\PawLoyalty\PawLoyalty.Web\Controllers\PetBookingController.cs:line 243
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
UPDATE
It's coming through BasicRepository is as below.All repositories have been inherited from this.
public class BasicRepository : IBasicRepository
{
private DataCatalog catalog;
protected DataCatalog Catalog { get { if (catalog == null) catalog = new DataCatalog(); return catalog; } }
public void Dispose() { if (catalog != null) catalog.Dispose(); }
}
Can I have any help ?

Related

Azure Cosmos DB - StartIndex cannot be less than zero. (Parameter 'startIndex')

I'm trying to insert a clan entity to Clan container. My partition key is id and the model is like this:
public class Clan
{
public string Id { get; set; }
public string ClanName { get; set; }
public int MembersCount { get; set; }
public int Capacity { get; set; }
public int WHP { get; set; }
public int LogoId { get; set; }
public AppMarketType AppMarket { get; set; }
}
ClanDbContext:
public class ClanContext : DbContext
{
public ClanContext(DbContextOptions<ClanContext> options)
: base(options) { }
public DbSet<Clan> Clans { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Clan>()
.HasNoDiscriminator()
.ToContainer("Clans")
.HasPartitionKey(p => p.Id)
.Property(x => x.Id).ToJsonProperty("id");
}
}
All I want to do is:
try
{
var clan = new Clan
{
Id = Guid.NewGuid().ToString(),
AppMarket = Core.AppMarketType.GooglePlay,
ClanName = "Blazers",
Capacity = 110,
LogoId = 342,
MembersCount = 34,
WHP = 1280
};
_clanContext.Add(clan);
_clanContext.SaveChanges();
}
catch (Exception)
{
throw;
}
It throws an exception:
StartIndex cannot be less than zero. (Parameter 'startIndex')
Callstack:
at System.Text.StringBuilder.Remove(Int32 startIndex, Int32 length)
at Microsoft.EntityFrameworkCore.Cosmos.ValueGeneration.Internal.IdValueGenerator.NextValue(EntityEntry entry)
at Microsoft.EntityFrameworkCore.ValueGeneration.ValueGenerator.Next(EntityEntry entry)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.ValueGenerationManager.Generate(InternalEntityEntry entry)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState entityState, Boolean acceptChanges, Boolean modifyProperties, Nullable`1 forceStateWhenUnknownKey)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode`1 node)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.AttachGraph(InternalEntityEntry rootEntry, EntityState targetState, EntityState storeGeneratedWithKeySetTargetState, Boolean forceStateWhenUnknownKey)
at Microsoft.EntityFrameworkCore.DbContext.SetEntityState(InternalEntityEntry entry, EntityState entityState)
at Microsoft.EntityFrameworkCore.DbContext.SetEntityState[TEntity](TEntity entity, EntityState entityState)
at Microsoft.EntityFrameworkCore.DbContext.Add[TEntity](TEntity entity)
at Dummy.Web.Services.ClanService.<IncreaseWHP>d__6.MoveNext() in C:\Repositories\dummysolution\Domain\dummydomain\Services\ClanService.cs:line 50
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Clans.JoinGroup.<Run>d__2.MoveNext() in C:\Repositories\dummysolution\API\dummyapi\Clans\JoinGroup.cs:line 55
After confirm with contributor, this issue was fixed in Microsoft.EntityFrameworkCore.Cosmos 5.0.0.
If you are using a version before 5.0.0, please try after upgrading.
If you are getting a similar exception in 5.0.0 or later please file a new issue and include a small project that demonstrates it.
Related Issue:
Cannot create new item in collection

Create a complex type model validation attribute with server and client validation

I'm trying to create an attribute that can validate a complex type both on the server and client side. This attribute will be used for required and non required complex types such as the following Address Class
public partial class AddressViewModel
{
[DisplayName("Address 1")]
[MaxLength(100)]
public virtual string Address1 { get; set; }
[DisplayName("Address 2")]
[MaxLength(100)]
public virtual string Address2 { get; set; }
[MaxLength(100)]
public virtual string City { get; set; }
[MaxLength(50)]
public virtual string State { get; set; }
[MaxLength(10)]
[DisplayName("Postal Code")]
public virtual string PostalCode { get; set; }
[MaxLength(2)]
public virtual string Country { get; set; }
}
The problem is that this model could be required sometimes and optional other times. I know that I could simply create another RequiredAddressViewModel class that has the Required attribute associated with the properties I deem required. I feel like there could be a reusable solution, such as a ValidationAttribute.
I created the following classes and they work server side, but do not work for client side.
public class AddressIfAttribute : ValidationAttribute, IClientValidatable
{
public string Address1 { get; private set; }
public string Address2 { get; private set; }
public string City { get; private set; }
public string State { get; private set; }
public string PostalCode { get; private set; }
public string Country { get; private set; }
public bool IsRequired { get; private set; }
public AddressIfAttribute(bool isRequired) : base("The field {0} is required.")
{
IsRequired = isRequired;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var address = value as AddressViewModel;
Address1 = address.Address1;
Address2 = address.Address2;
City = address.City;
State = address.State;
Country = address.Country;
PostalCode = address.PostalCode;
var results = new List<ValidationResult>();
var context = new ValidationContext(address, null, null);
Validator.TryValidateObject(address, context, results, true);
if (results.Count == 0 && IsRequired)
{
if (string.IsNullOrEmpty(Address2))
return new ValidationResult(string.Format(ErrorMessageString, validationContext.DisplayName));
}
else if (results.Count != 0)
{
var compositeResults = new CompositeValidationResult(string.Format("Validation for {0} failed!", validationContext.DisplayName));
results.ForEach(compositeResults.AddResult);
return compositeResults;
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
return new[]
{
new ModelClientValidationAddressIfRule(string.Format(ErrorMessageString,metadata.GetDisplayName()), Address1, Address2, City, State, Country, PostalCode,IsRequired)
};
}
}
public class ModelClientValidationAddressIfRule : ModelClientValidationRule
{
public ModelClientValidationAddressIfRule(string errorMessage, object address1, object address2, object city, object state, object country, object postalCode, bool isRequired)
{
ErrorMessage = errorMessage;
ValidationType = "addressif";
ValidationParameters.Add("address1", address1);
ValidationParameters.Add("address2", address2);
ValidationParameters.Add("city", city);
ValidationParameters.Add("state", state);
ValidationParameters.Add("country", country);
ValidationParameters.Add("postalCode", postalCode);
ValidationParameters.Add("isrequired", isRequired.ToString().ToLower());
}
Since the AddressIf attribute is on a complex type the necessary markup isn't added and unobtrusive javascript doesn't validate these fields.
So if I want the rendered HTML to have the proper data-* fields, is my only solution to create another RequiredAddressViewModel? At this point, it might be the easiest.

Handling WCF services in orchard and integration with orchard notification

Here is my case, I wrote a wcf and it is working with orchard perfectly.
I'm going to handle events messages such as warnings and exceptions so I add a ServiceAdapter
and ClientServiceLocator to my project :
ServiceAdapter:
public class ServiceAdapter<TService>
where TService : class, IContract
{
public TResult Execute<TResult>(Func<TService, TResult> command)
where TResult : IDtoResponseEnvelop
{
try
{
var dispatcher = ClientServiceLocator.Instance().CommandDispatcher;
var result = DispatchCommand(() => dispatcher.ExecuteCommand(command));
if (result.Response.HasWarning)
{
ClientServiceLocator.Instance()
.WarningManager
.HandleBusinessWarning(result.Response.BusinessWarnings);
}
if (result.Response.HasException)
{
ClientServiceLocator.Instance()
.ExceptionManager
.HandleBusinessException(result.Response.BusinessException);
}
return result;
}
finally
{
}
}
private static TResult DispatchCommand<TResult>(Func<TResult> dispatcherCommand)
where TResult : IDtoResponseEnvelop
{
var asynchResult = dispatcherCommand.BeginInvoke(null, null);
while (!asynchResult.IsCompleted)
{
}
return dispatcherCommand.EndInvoke(asynchResult);
}
}
ClientServiceLocator:
public class ClientServiceLocator
{
static readonly Object LocatorLock = new object();
private static ClientServiceLocator InternalInstance;
private ClientServiceLocator() { }
public static ClientServiceLocator Instance()
{
if (InternalInstance == null)
{
lock (LocatorLock)
{
// in case of a race scenario ... check again
if (InternalInstance == null)
{
InternalInstance = new ClientServiceLocator();
}
}
}
return InternalInstance;
}
#region IClientServices Members
public IBusinessExceptionManager ExceptionManager { get; set; }
public IBusinessWarningManager WarningManager { get; set; }
public ICommandDispatcher CommandDispatcher { get; set; }
#endregion
}
BusinessExceptionManager:
class BusinessExceptionManager
: IBusinessExceptionManager, IDependency
{
private Localizer T { get; set; }
private readonly INotifier _notifier;
public BusinessExceptionManager(INotifier notifier)
{
_notifier = notifier;
T = NullLocalizer.Instance;
}
public void HandleBusinessException(BusinessExceptionDto exceptionDto)
{
_notifier.Add(NotifyType.Error, T(exceptionDto.Message));
}
}
BusinessWarningManager:
class BusinessWarningManager
: IBusinessWarningManager, IDependency
{
private Localizer T { get; set; }
private readonly INotifier _notifier;
public BusinessWarningManager(INotifier notifier)
{
_notifier = notifier;
T = NullLocalizer.Instance;
}
public void HandleBusinessWarning(IEnumerable<BusinessWarning> warnings)
{
var message = string.Join(Environment.NewLine, warnings.Select(w => w.Message));
_notifier.Add(NotifyType.Warning, T(message));
}
}
Here is the controller:
public class SectorsAdminController : Controller
{
private dynamic Shape { get; set; }
private Localizer T { get; set; }
private readonly INotifier _notifier;
private readonly ISiteService _siteService;
private ServiceAdapter<ISectorService> _sectorServiceAdapter;
public SectorsAdminController(ISiteService siteService, INotifier notifier, IShapeFactory shapeFactory)
{
Shape = shapeFactory;
T = NullLocalizer.Instance;
_notifier = notifier;
_siteService = siteService;
_sectorServiceAdapter = new ServiceAdapter<ISectorService>();
}
public ActionResult Index()
{
var model = Shape.Sectors(Sectors: _sectorServiceAdapter.Execute(s => s.FindAll()).Sectors);
return View((object)model);
}
}
Here is the error:
Oops. Something went wrong ... sorry
An unhandled exception has occurred and the request was terminated. Please refresh the page. If the error persists, go back
Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object. Server stack trace: at SAS.Admin.Services.ServiceAdapter1.<>c__DisplayClass31.b__0() at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs) at System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage msg, IMessageSink replySink) Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.EndInvokeHelper(Message reqMsg, Boolean bProxyCase) at System.Runtime.Remoting.Proxies.RemotingProxy.Invoke(Object NotUsed, MessageData& msgData) at System.Func1.EndInvoke(IAsyncResult result) at SAS.Admin.Services.ServiceAdapter1.Execute[TResult](Func2 command) at SAS.Admin.Controllers.SectorsAdminController.Index() at lambda_method(Closure , ControllerBase , Object[] ) at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3f() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass48.b__41() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass48.b__41()
Why would you use a Poor's Man Singleton? I would start by using ISingletonDependency on your IClientServices members, if that is what you need
Get rid of the horrible ServiceLocator, then add IDependency to your ServiceAdapter.
As matter of fact change everything to let Orchard handle instantiation. I do not see why your ServiceAdapter could not be a simple Service instantiated by your Controller, then each one of your IClientServices created as Providers in your Service.

Entity Framework -- An item with the same key has already been added

I am having an intermittent error that I am not able to figure out. When my application is starting up the following line gives me the error stated in the title.
IList<DataAgentStatus> list = dbContext.DataAgentStatus.ToList();
The "DataAgentStatus" table only has 12 rows in it and the primary key is a string with unique names in it.
Any thoughts or ideas on where I should look? Most times if I hit "Continue" the application runs fine.
DataAgentStatus class (NotificationObject is a prism object that implements INotifyPropertyChanged)
public class DataAgentStatus : NotificationObject
{
[Key]
public string DataAgentName { get; set; }
public DateTime? LastAccessDate { get; set; }
public bool ErrorState { get; set; }
public string ErrorMessage { get; set; }
public int? Quantity { get; set; }
public DateTime? CreatedDate { get; set; }
public DateTime? LastModifiedDate { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
}
}
Entry on the DbContext class
public DbSet<DataAgentStatus> DataAgentStatus { get; set; }
Call Stack from error.
at System.Collections.Generic.Dictionary2.Insert(TKey key, TValue value, Boolean add)
at System.Data.Objects.ObjectStateManager.AddEntityEntryToDictionary(EntityEntry entry, EntityState state)
at System.Data.Objects.ObjectStateManager.AddEntry(IEntityWrapper wrappedObject, EntityKey passedKey, EntitySet entitySet, String argumentName, Boolean isAdded)
at System.Data.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet)
at lambda_method(Closure , Shaper )
at System.Data.Common.Internal.Materialization.Coordinator1.ReadNextElement(Shaper shaper)
at System.Data.Common.Internal.Materialization.Shaper1.SimpleEnumerator.MoveNext()
at System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at WPF.Data.Models.DataAgentStatus.List(DataBroker dbContext) in c:\Projects\WPF - Trunk\src\Components\Framework.WPF\Data\Models\DataAgentStatus.cs:line 88
at Framework.WPF.Data.Models.DataAgentStatus.ReloadObjects(DataBroker dbContext) in c:\Projects\WPF - Trunk\src\Components\Framework.WPF\Data\Models\DataAgentStatus.cs:line 101
at WPF.Data.Models.DataAgentStatus.LoadByType(DataBroker dbContext, String statusName, Boolean forceReload) in c:\Projects\WPF - Trunk\src\Components\Framework.WPF\Data\Models\DataAgentStatus.cs:line 73
at Framework.WPF.Data.Models.DataAgentStatus.LoadByType(DataBroker dbContext, String statusName) in c:\Projects\WPF - Trunk\src\Components\Framework.WPF\Data\Models\DataAgentStatus.cs:line 66
at Base.Data.Handlers.ReferenceDataHandler.GetUserWebLinks(ReceivingDatabroker dbContext) in c:\Projects\WPF - Trunk\src\Receiving\Receiving.Base\Data\Handlers\ReferenceDataHandler.cs:line 40
at Base.Data.Agents.UserWebLinkDataAgent.UserLinks(ReceivingDatabroker dbContext) in c:\Projects\WPF - Trunk\src\Receiving\Receiving.Base\Data\Agents\UserWebLinkDataAgent.cs:line 41
at Receiving.Base.Data.Handlers.LoginHandler.timmy_Elapsed(Object sender, ElapsedEventArgs e) in c:\Projects\WPF - Trunk\src\Receiving\Receiving.Base\Data\Handlers\LoginHandler.cs:line 144
at System.Timers.Timer.MyTimerCallback(Object state)

How to use automapper?

I have domain class with following definition
public class Category : EntityBase<int>
{
public string Name { get; set; }
public string Description { get; set; }
}
And this class is inherited from a common abstract class
public abstract class EntityBase<TId>
{
public TId Id { get; set; }
}
And my ServiceModel class for this type is look like
public class CategoryDto
{
public string Name { get; set; }
public string Description { get; set; }
public int CategoryId { get; set; }
}
to convert between object i am using automapper. i configured automapper like this
public class AutoMapperServiceConfigurations
{
public static void Configure()
{
Mapper.Initialize(conf => conf.AddProfile(new CategoryProfile()));
}
}
public class CategoryProfile : Profile
{
protected override void Configure()
{
Mapper.CreateMap<Category,CategoryDto>();
}
}
to convert objects when i used automapper in my code it shows some error, my code is given below
var categoryCollection= _categoryRepository.Get<Category>();
// Mapping section here i got error
var returnCollection =
Mapper.Map<IQueryable<Category>, IQueryable<CategoryDto>> (categoryCollection);
return returnCollection;
and the error is
<Error><Message>An error has occurred.</Message><ExceptionMessage>
Unable to cast object of type
'System.Collections.Generic.List`1[PCD.Service.ServiceModels.CategoryDto]' to type 'System.Linq.IQueryable`1[PCD.Service.ServiceModels.CategoryDto]'.
</ExceptionMessage><ExceptionType>System.InvalidCastException</ExceptionType><StackTrace> at AutoMapper.MappingEngine.Map[TSource,TDestination](TSource source)
at AutoMapper.Mapper.Map[TSource,TDestination](TSource source)
at PCD.Service.Implimentations.CategoryService.Read[T]() in g:\AngularJs Practise\ProofOfConceptDemo.Solution\PCD.Service\Implimentations\CategoryService.cs:line 50
at PCD.WebApi.Controllers.CategoryController.Get() in g:\AngularJs Practise\ProofOfConceptDemo.Solution\PCD.WebApi\Controllers\CategoryController.cs:line 23
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.<>c__DisplayClass5.<ExecuteAsync>b__4()
at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)</StackTrace></Error>
You will want to use the queryable extensions:
http://docs.automapper.org/en/stable/Queryable-Extensions.html
var categoryCollection = _categoryRepository.Get<Category>();
var returnCollection = categoryCollection.ProjectTo<CategoryDto>();
return returnCollection.ToList();

Resources