Hello Halil,
I have an urgent requirement that kind of aligns at the intersection of Tenants and OUs. Our company has acquired multiple small companies, and we want to create users in the system from each company. However, some of the users may belong to multiple companies as well.
When the user logs in, if they are members of multiple companies, then I want to show them an option to select which company they want to manage. They select one and that loads the app with the features and permissions for that company. They should have the ability to switch to another company and manage things in for another company.
For some staff, once they are set up they might never see the menu to select company because they belong to only one company.
What is the best way to achieve this? I would greatly appreciate if you could elaborate a little bit on how to achieve this quickly.
Thanks in advance! Nipun
I have written my first test case.But unfortunately it gives below mentioned exception :cry: Could you tell me why ? Thanks.
Test case :
public class AcquisitionTypeAppServiceTests : AppTestBase
{
private readonly IAcquisitionTypeAppService _acquisitionTypeAppService;
public AcquisitionTypeAppServiceTests()
{
_acquisitionTypeAppService = Resolve<IAcquisitionTypeAppService>();
}
[Fact]
public async Task Test_GetAllAcquisitionTypesAsync()
{
//Act
var acquisitionTypes = await _acquisitionTypeAppService.GetAllAcquisitionTypesAsync();
//Assert
acquisitionTypes.Items.Count.ShouldBe(5);
}
}
Exception :
Test Name: IP.Tests.AcquisitionTypes.AcquisitionTypeAppServiceTests.Test_GetAllAcquisitionTypesAsync
Test FullName: IP.Tests.AcquisitionTypes.AcquisitionTypeAppServiceTests.Test_GetAllAcquisitionTypesAsync
Test Source: \Tests\IP.Tests\AcquisitionTypes\AcquisitionTypeAppServiceTests.cs : line 19
Test Outcome: Failed
Test Duration: 0:00:00.001
Result Message:
System.Data.Entity.Infrastructure.DbUpdateException : An error occurred while updating the entries. See the inner exception for details.
---- System.Data.Entity.Core.UpdateException : An error occurred while updating the entries. See the inner exception for details.
-------- System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation.
------------ NMemory.Exceptions.ForeignKeyViolationException : Foreign key violation [IpProperties :: CountyId]. The key value [3] does not exists in the referenced table [IpCounties :: Id].. Error code: RelationError
Result StackTrace:
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at Abp.EntityFramework.AbpDbContext.SaveChanges()
at Joshi.IP.Migrations.Seed.InitialPropertiesCreator.Create() in d:\Freelance Work\Nipun-SPA\SPA\island\Joshi.IP.EntityFramework\Migrations\Seed\InitialPropertiesCreator.cs:line 111
at Joshi.IP.Migrations.Seed.InitialDbBuilder.Create() in d:\Freelance Work\Nipun-SPA\SPA\island\Joshi.IP.EntityFramework\Migrations\Seed\InitialDbBuilder.cs:line 22
at Joshi.IP.Tests.AppTestBase.<.ctor>b__0(IpDbContext context) in d:\Freelance Work\Nipun-SPA\SPA\island\Tests\Joshi.IP.Tests\AppTestBase.cs:line 36
at Joshi.IP.Tests.AppTestBase.UsingDbContext(Action`1 action) in d:\Freelance Work\Nipun-SPA\SPA\island\Tests\Joshi.IP.Tests\AppTestBase.cs:line 70
at Joshi.IP.Tests.AppTestBase..ctor() in d:\Freelance Work\Nipun-SPA\SPA\island\Tests\Joshi.IP.Tests\AppTestBase.cs:line 34
at Joshi.IP.Tests.AcquisitionTypes.AcquisitionTypeAppServiceTests..ctor() in d:\Freelance Work\Nipun-SPA\SPA\island\Tests\Joshi.IP.Tests\AcquisitionTypes\AcquisitionTypeAppServiceTests.cs:line 12
----- Inner Stack Trace -----
at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut)
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction)
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal>b__27()
at System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
----- Inner Stack Trace -----
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Effort.Internal.Common.DatabaseReflectionHelper.InsertEntity(ITable table, Object entity, Transaction transaction)
at Effort.Internal.CommandActions.InsertCommandAction.CreateAndInsertEntity(ITable table, IList`1 memberBindings, Transaction transaction)
at Effort.Internal.CommandActions.InsertCommandAction.ExecuteDataReader(ActionContext context)
at Effort.Provider.EffortEntityCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c)
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
----- Inner Stack Trace -----
at NMemory.Tables.Relation`4.ValidateEntityCore(TForeign foreign)
at NMemory.Tables.Relation`4.NMemory.Tables.IRelationInternal.ValidateEntity(Object foreign)
at NMemory.Execution.ExecutionHelper.ValidateForeignKeys(IList`1 relations, IEnumerable`1 referringEntities)
at NMemory.Execution.CommandExecutor.ExecuteInsert[T](T entity, IExecutionContext context)
at NMemory.Tables.DefaultTable`2.InsertCore(TEntity entity, Transaction transaction)
at Effort.Internal.DbManagement.Engine.ExtendedTable`2.InsertCore(TEntity entity, Transaction transaction)
at NMemory.Tables.Table`2.Insert(TEntity entity, Transaction transaction)
at Effort.Internal.Common.DatabaseReflectionHelper.WrapperMethods.InsertEntity[TEntity](ITable`1 table, TEntity entity, Transaction transaction)
I have upgraded to the latest version (1.7).Now it gives below mentioned error when I try to load the app.Could you tell me why ? Thanks in advance.
Error url : [https://docs.angularjs.org/error/$injector/modulerr?p0=app&p1=Error:%20%5B$injector:modulerr%5D%20http:%2F%2Ferrors.angularjs.org%2F1.4.8%2F$injector%2Fmodulerr%3Fp0%3Doc.lazyLoad%26p1%3DError%253A%2520%255B%2524injector%253Anomod%255D%2520http%253A%252F%252Ferrors.angularjs.org%252F1.4.8%252F%2524injector%252Fnomod%253Fp0%253Dxeditable%250A%2520%2520%2520%2520at%2520Error%2520(native)%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%253A6240%252FScripts%252Fangular.min.js%253A6%253A416%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%253A6240%252FScripts%252Fangular.min.js%253A24%253A186%250A%2520%2520%2520%2520at%2520b%2520(http%253A%252F%252Flocalhost%253A6240%252FScripts%252Fangular.min.js%253A23%253A251)%250A%2520%2520%2520%2520at%2520Object.module%2520(http%253A%252F%252Flocalhost%253A6240%252FScripts%252Fangular.min.js%253A23%253A494)%250A%2520%2520%2520%2520at%2520u%2520(http%253A%252F%252Flocalhost%253A6240%252Flibs%252Fangular-ocLazyLoad%252FocLazyLoad.min.js%253A8%253A2925)%250A%2520%2520%2520%2520at%2520Object.n%2520%255Bas%2520forEach%255D%2520(http%253A%252F%252Flocalhost%253A6240%252FScripts%252Fangular.min.js%253A7%253A333)%250A%2520%2520%2520%2520at%2520u%2520(http%253A%252F%252Flocalhost%253A6240%252Flibs%252Fangular-ocLazyLoad%252FocLazyLoad.min.js%253A8%253A2994)%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%253A6240%252Flibs%252Fangular-ocLazyLoad%252FocLazyLoad.min.js%253A8%253A3048%250A%2520%2520%2520%2520at%2520Object.n%2520%255Bas%2520forEach%255D%2520(http%253A%252F%252Flocalhost%253A6240%252FScripts%252Fangular.min.js%253A7%253A333)%0A%20%20%20%20at%20Error%20(native)%0A%20%20%20%20at%20http:%2F%2Flocalhost:6240%2FScripts%2Fangular.min.js:6:416%0A%20%20%20%20at%20http:%2F%2Flocalhost:6240%2FScripts%2Fangular.min.js:38:391%0A%20%20%20%20at%20n%20(http:%2F%2Flocalhost:6240%2FScripts%2Fangular.min.js:7:333)%0A%20%20%20%20at%20g%20(http:%2F%2Flocalhost:6240%2FScripts%2Fangular.min.js:37:488)%0A%20%20%20%20at%20http:%2F%2Flocalhost:6240%2FScripts%2Fangular.min.js:38:134%0A%20%20%20%20at%20n%20(http:%2F%2Flocalhost:6240%2FScripts%2Fangular.min.js:7:333)%0A%20%20%20%20at%20g%20(http:%2F%2Flocalhost:6240%2FScripts%2Fangular.min.js:37:488)%0A%20%20%20%20at%20eb%20(http:%2F%2Flocalhost:6240%2FScripts%2Fangular.min.js:41:249)%0A%20%20%20%20at%20c%20(http:%2F%2Flocalhost:6240%2FScripts%2Fangular.min.js:19:463])
Here it shows the error :
This is my whole app.js file.
/* 'app' MODULE DEFINITION */
var appModule = angular.module("app", [
"ui.router",
"ui.bootstrap",
'ui.utils',
"ui.jq",
'ui.grid',
'ui.grid.pagination',
"oc.lazyLoad",
"ngSanitize",
'angularFileUpload',
'daterangepicker',
'xeditable',
'abp'
]);
/* LAZY LOAD CONFIG */
/* This application does not define any lazy-load yet but you can use $ocLazyLoad to define and lazy-load js/css files.
* This code configures $ocLazyLoad plug-in for this application.
* See it's documents for more information: https://github.com/ocombe/ocLazyLoad
*/
appModule.config(['$ocLazyLoadProvider', function ($ocLazyLoadProvider) {
$ocLazyLoadProvider.config({
cssFilesInsertBefore: 'ng_load_plugins_before', // load the css files before a LINK element with this ID.
debug: false,
events: true,
modules: []
});
}]);
/* THEME SETTINGS */
App.setAssetsPath(abp.appPath + 'metronic/assets/');
appModule.factory('settings', ['$rootScope', function ($rootScope) {
var settings = {
layout: {
pageSidebarClosed: false, // sidebar menu state
pageContentWhite: true, // set page content layout
pageBodySolid: false, // solid body color state
pageAutoScrollOnLoad: 1000 // auto scroll to top on page load
},
layoutImgPath: App.getAssetsPath() + 'admin/layout4/img/',
layoutCssPath: App.getAssetsPath() + 'admin/layout4/css/',
assetsPath: abp.appPath + 'metronic/assets',
globalPath: abp.appPath + 'metronic/assets/global',
layoutPath: abp.appPath + 'metronic/assets/layouts/layout4'
};
$rootScope.settings = settings;
return settings;
}]);
/* ROUTE DEFINITIONS */
appModule.config([
'$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
// Default route (overrided below if user has permission)
$urlRouterProvider.otherwise("/welcome");
//Welcome page
$stateProvider.state('welcome', {
url: '/welcome',
templateUrl: '~/App/common/views/welcome/index.cshtml'
});
//COMMON routes
if (abp.auth.hasPermission('Pages.Administration.Roles')) {
$stateProvider.state('roles', {
url: '/roles',
templateUrl: '~/App/common/views/roles/index.cshtml',
menu: 'Administration.Roles'
});
}
if (abp.auth.hasPermission('Pages.Administration.Users')) {
$stateProvider.state('users', {
url: '/users',
templateUrl: '~/App/common/views/users/index.cshtml',
menu: 'Administration.Users'
});
}
if (abp.auth.hasPermission('Pages.Administration.Languages')) {
$stateProvider.state('languages', {
url: '/languages',
templateUrl: '~/App/common/views/languages/index.cshtml',
menu: 'Administration.Languages'
});
if (abp.auth.hasPermission('Pages.Administration.Languages.ChangeTexts')) {
$stateProvider.state('languageTexts', {
url: '/languages/texts/:languageName?sourceName&baseLanguageName&targetValueFilter&filterText',
templateUrl: '~/App/common/views/languages/texts.cshtml',
menu: 'Administration.Languages'
});
}
}
if (abp.auth.hasPermission('Pages.Administration.AuditLogs')) {
$stateProvider.state('auditLogs', {
url: '/auditLogs',
templateUrl: '~/App/common/views/auditLogs/index.cshtml',
menu: 'Administration.AuditLogs'
});
}
if (abp.auth.hasPermission('Pages.Administration.OrganizationUnits')) {
$stateProvider.state('organizationUnits', {
url: '/organizationUnits',
templateUrl: '~/App/common/views/organizationUnits/index.cshtml',
menu: 'Administration.OrganizationUnits'
});
}
//HOST routes
$stateProvider.state('host', {
'abstract': true,
url: '/host',
template: '<div ui-view class="fade-in-up"></div>'
});
if (abp.auth.hasPermission('Pages.Tenants')) {
$urlRouterProvider.otherwise("/host/tenants"); //Entrance page for the host
$stateProvider.state('host.tenants', {
url: '/tenants',
templateUrl: '~/App/host/views/tenants/index.cshtml',
menu: 'Tenants'
});
}
if (abp.auth.hasPermission('Pages.Editions')) {
$stateProvider.state('host.editions', {
url: '/editions',
templateUrl: '~/App/host/views/editions/index.cshtml',
menu: 'Editions'
});
}
if (abp.auth.hasPermission('Pages.Administration.Host.Settings')) {
$stateProvider.state('host.settings', {
url: '/settings',
templateUrl: '~/App/host/views/settings/index.cshtml',
menu: 'Administration.Settings.Host'
});
}
//TENANT routes
$stateProvider.state('tenant', {
'abstract': true,
url: '/tenant',
template: '<div ui-view class="fade-in-up"></div>'
});
if (abp.auth.hasPermission('Pages.Tenant.Dashboard')) {
$urlRouterProvider.otherwise("/tenant/dashboard"); //Entrace page for a tenant
$stateProvider.state('tenant.dashboard', {
url: '/dashboard',
templateUrl: '~/App/tenant/views/dashboard/index.cshtml',
menu: 'Dashboard.Tenant'
});
}
if (abp.auth.hasPermission('Pages.Administration.Tenant.Settings')) {
$stateProvider.state('tenant.settings', {
url: '/settings',
templateUrl: '~/App/tenant/views/settings/index.cshtml',
menu: 'Administration.Settings.Tenant'
});
}
if (abp.auth.hasPermission('Pages.Tenant.PropertyManagement')) {
$stateProvider.state('tenant.propertymanagement', {
url: '/propertymanagement',
templateUrl: '~/App/tenant/views/propertymanagement/index.cshtml',
menu: 'PropertyManagement.Tenant'
});
}
$stateProvider.state('tenant.imports', {
url: '/imports',
templateUrl: '~/App/tenant/views/imports/index.cshtml',
menu: 'Imports'
});
$stateProvider.state('tenant.propertyListingsReport', {
url: '/propertyListingsReport',
templateUrl: '~/App/tenant/views/reports/propertyListings.cshtml',
menu: 'PropertyListingsReport.Tenant'
});
$stateProvider.state('tenant.PaymentReceived', {
url: '/PaymentReceived',
templateUrl: '~/App/tenant/views/reports/bpoReports/paymentReceived.cshtml',
menu: 'PaymentReceived.Tenant'
});
$stateProvider.state('tenant.BankReport', {
url: '/BankReport',
templateUrl: '~/App/tenant/views/reports/bpoReports/bankReport.cshtml',
menu: 'BankReport.Tenant'
});
$stateProvider.state('tenant.OwnerInformation', {
url: '/OwnerInformation',
templateUrl: '~/App/tenant/views/reports/researchInformation/ownerInformation.cshtml',
menu: 'OwnerInformation.Tenant'
});
$stateProvider.state('tenant.DriveByRequested', {
url: '/DriveByRequested',
templateUrl: '~/App/tenant/views/reports/researchInformation/driveByRequested.cshtml',
menu: 'DriveByRequested.Tenant'
});
$stateProvider.state('tenant.PotentialPropertiesToConsider', {
url: '/PotentialPropertiesToConsider',
templateUrl: '~/App/tenant/views/reports/researchInformation/potentialPropertiesToConsider.cshtml',
menu: 'PotentialPropertiesToConsider.Tenant'
});
$stateProvider.state('tenant.BankListUpcoming', {
url: '/BankListUpcoming',
templateUrl: '~/App/tenant/views/reports/researchInformation/bankListUpcoming.cshtml',
menu: 'BankListUpcoming.Tenant'
});
$stateProvider.state('tenant.AttorneyForBankUpcoming', {
url: '/AttorneyForBankUpcoming',
templateUrl: '~/App/tenant/views/reports/researchInformation/attorneyForBankUpcoming.cshtml',
menu: 'AttorneyForBankUpcoming.Tenant'
});
$stateProvider.state('tenant.UpcomingForeclosureSalesAll', {
url: '/UpcomingForeclosureSalesAll',
templateUrl: '~/App/tenant/views/reports/upcomingForeclosureSales/upcomingForeclosureSalesAll.cshtml',
menu: 'UpcomingForeclosureSalesAll.Tenant'
});
$stateProvider.state('tenant.UpcomingForeclosureSalesPriority1List', {
url: '/UpcomingForeclosureSalesPriority1List',
templateUrl: '~/App/tenant/views/reports/upcomingForeclosureSales/upcomingForeclosureSalesPriority1List.cshtml',
menu: 'UpcomingForeclosureSalesPriority1List.Tenant'
});
$stateProvider.state('tenant.UpcomingForeclosureSalesByAgent', {
url: '/UpcomingForeclosureSalesByAgent',
templateUrl: '~/App/tenant/views/reports/upcomingForeclosureSales/UpcomingForeclosureSalesByAgent.cshtml',
menu: 'UpcomingForeclosureSalesByAgent.Tenant'
});
$stateProvider.state('tenant.BankEvaluation', {
url: '/BankEvaluation',
templateUrl: '~/App/tenant/views/reports/reports/bankEvaluation.cshtml',
menu: 'BankEvaluation.Tenant'
});
$stateProvider.state('tenant.AttorneyEvaluation', {
url: '/AttorneyEvaluation',
templateUrl: '~/App/tenant/views/reports/reports/attorneyEvaluation.cshtml',
menu: 'AttorneyEvaluation.Tenant'
});
}
]);
appModule.run(["$rootScope", "settings", "$state", function ($rootScope, settings, $state) {
$rootScope.$state = $state;
$rootScope.$settings = settings;
$rootScope.safeApply = function (fn) {
var phase = this.$root.$$phase;
if (phase == '$apply' || phase == '$digest') {
if (fn && (typeof (fn) === 'function')) {
fn();
}
} else {
this.$apply(fn);
}
};
}]);
I'm very new to this framework.So I have successfully upgraded all the nugget packages for the V 0.7.6.But now I need to upgrade the AspNet Zero v1.7 too.So I have a few questions.Hope you'll give feedback for those.Thanks in advance.
How do I know which version (AspNet Zero) currently on my project ?
What is the easiest way to upgrade my project into above version (may be the steps) ?
I have successfully updated the V 0.7.6.But now it gives below mentioned error on the Entity Framework project.Could you tell me how to sorted it out ? Thanks in advance.
Error 4 'IP.Editions.EditionManager' does not contain a definition for 'DefaultEditionName' IP.EntityFramework\Migrations\Seed\DefaultEditionCreator.cs 27 119 IP.EntityFramework
This is the problemed method on DefaultEditionCreator.cs
private void CreateEditions()
{
var defaultEdition = _context.Editions.FirstOrDefault(e => e.Name == EditionManager.DefaultEditionName);
if (defaultEdition == null)
{
defaultEdition = new Edition { Name = EditionManager.DefaultEditionName, DisplayName = EditionManager.DefaultEditionName };
_context.Editions.Add(defaultEdition);
_context.SaveChanges();
//TODO: Add desired features to the standard edition, if wanted!
}
}
I have created Properties Management App with UI following the phonebook sample app for ASP.NET ZERO. I have multiple tabs on the Create Property popup, to segregate the UI contexts.
I can successully Create and Save a property listing. I can also open a listing and edit it and Save it. But, when I Create New Listing and Save the records, and want to edit without closing the popup , it's throwing an error. Note that since I have multiple tabs, I am not closing the popup at successful Save response.
Also, it after creating the record, the system is returning the newly created propertyId back all the way to the UI. That's the Id value that I send for the Edit action, that gets passed to EditPropertyAsync() that I have defined for Edit flow. I am trying to use the same method, sending it the Id that just got created, with only difference that I have not closed the popup and am trying to edit on the Create window itself.
Here's the log:
ERROR 2015-11-19 10:38:16,338 [16 ] lers.Filters.AbpExceptionFilterAttribute - AutoMapper.AutoMapperMappingException:
Mapping types:
Int32 -> Int32
System.Int32 -> System.Int32
Destination path:
Property.Address.Address.Id.Id
Source value:
0 ---> System.InvalidOperationException: The property 'Id' is part of the object's key information and cannot be modified.
at System.Data.Entity.Core.Objects.EntityEntry.VerifyEntityValueIsEditable(StateManagerTypeMetadata typeMetadata, Int32 ordinal, String memberName)
at System.Data.Entity.Core.Objects.EntityEntry.GetAndValidateChangeMemberInfo(String entityMemberName, Object complexObject, String complexObjectMemberName, StateManagerTypeMetadata& typeMetadata, String& changingMemberName, Object& changingObject)
at System.Data.Entity.Core.Objects.EntityEntry.EntityMemberChanging(String entityMemberName, Object complexObject, String complexObjectMemberName)
at System.Data.Entity.Core.Objects.EntityEntry.EntityMemberChanging(String entityMemberName)
at System.Data.Entity.Core.Objects.ObjectStateEntry.System.Data.Entity.Core.Objects.DataClasses.IEntityChangeTracker.EntityMemberChanging(String entityMemberName)
at System.Data.Entity.DynamicProxies.Address_DC03C9817912E18A8FAA931110EEEF10FBB1519A7553CF5CAA7822ECD0C0FCBF.EntityMemberChanging(String )
at System.Data.Entity.DynamicProxies.Address_DC03C9817912E18A8FAA931110EEEF10FBB1519A7553CF5CAA7822ECD0C0FCBF.set_Id(Int32 )
at lambda_method(Closure , Object , Object )
at AutoMapper.Internal.PropertyAccessor.SetValue(Object destination, Object value)
at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.AssignValue(PropertyMap propertyMap, Object mappedObject, Object propertyValueToAssign)
at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.MapPropertyValue(ResolutionContext context, IMappingEngineRunner mapper, Object mappedObject, PropertyMap propertyMap)
--- End of inner exception stack trace ---
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)
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)
at AutoMapper.MappingEngine.MapCore(Object source, Object destination, Type sourceType, Type destinationType, MappingOperationOptions options)
at AutoMapper.MappingEngine.Map[TSource,TDestination](TSource source, TDestination destination, Action`1 opts)
at AutoMapper.MappingEngine.Map[TSource,TDestination](TSource source, TDestination destination)
at AutoMapper.Mapper.Map[TSource,TDestination](TSource source, TDestination destination)
at Abp.AutoMapper.AutoMapExtensions.MapTo[TSource,TDestination](TSource source, TDestination destination)
at Joshi.IP.IpProperties.PropertyAppService.<EditPropertyAsync>d__11.MoveNext() in d:\Freelance Work\Nipun-SPA\SPA\island\Joshi.IP.Application\IpProperties\PropertyAppService.cs:line 77
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Joshi.IP.IpProperties.PropertyAppService.<CreateOrEditPropertyAsync>d__5.MoveNext() in d:\Freelance Work\Nipun-SPA\SPA\island\Joshi.IP.Application\IpProperties\PropertyAppService.cs:line 52
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Abp.Threading.InternalAsyncHelper.<AwaitTaskWithPostActionAndFinallyAndGetResult>d__10`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Abp.Threading.InternalAsyncHelper.<AwaitTaskWithFinallyAndGetResult>d__c`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__3`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Abp.Extensions.ExceptionExtensions.ReThrow(Exception exception)
at Abp.WebApi.Controllers.Dynamic.Selectors.DynamicHttpActionDescriptor.<ExecuteAsync>b__0(Task`1 task)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at System.Web.Http.Controllers.AuthenticationFilterResult.<ExecuteAsync>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()
Here are the different code snippets that get involved at different points:
public async Task<int> CreatePropertyAsync(CreateOrEditPropertyInput input)
{
var property = input.Property.MapTo<Property>();
var propertyId = await _propertyRepository.InsertAndGetIdAsync(property);
return propertyId;
}
public async Task<int?> EditPropertyAsync(CreateOrEditPropertyInput input)
{
var property = await _propertyRepository.FirstOrDefaultAsync(p => p.Id == input.Property.Id);
input.Property.MapTo(property);
await _propertyRepository.UpdateAsync(property);
return input.Property.Id;
}
public class CreateOrEditPropertyInput : IInputDto
{
[Required]
public PropertyEditDto Property { get; set; }
}
[AutoMap(typeof(Property))]
public class PropertyEditDto
{
public const int MaxLength = 50;
public int? Id { get; set; }
public bool IsVacant { get; set; }
public bool IsPropertyToConsider { get; set; }
[Required]
[MaxLength(MaxLength)]
public string Dist { get; set; }
[Required]
[MaxLength(MaxLength)]
public string Sec { get; set; }
}
Javascript:
vm.init = function () {
propertyService.getPropertyForEdit({
id: vm.property.id
}).success(function (result) {
vm.property = result.property;
});
};
public async Task<GetPropertyForEditOutput> GetPropertyForEdit(NullableIdInput<int> input)
{
var output = new GetPropertyForEditOutput();
if (!input.Id.HasValue)//create
{
output.Property = new PropertyEditDto();
}
else //edit
{
var property = await _propertyRepository.FirstOrDefaultAsync(p => p.Id == input.Id.Value);
output.Property = property.MapTo<PropertyEditDto>();
}
return output;
}
public class GetPropertyForEditOutput : IOutputDto
{
public PropertyEditDto Property { get; set; }
}
Javascript:
//to save Property
function createOrEditProperty() {
vm.saving = true;
propertyService.createOrEditPropertyAsync({ property: vm.property }).success(function (data) {
vm.property.id = data;
abp.notify.info(app.localize('SavedSuccessfully'));
}).finally(function () {
vm.saving = false;
});
}
Thanks for the support!
I have an entity called Property and another entity called Address. They both need to have corresponding tables in the database. They have a one-to-one relationship.
The Property entity has PropertyId as the field which am setting to primary key using [key] attribute in the Property class, and in the Address class am setting PropertyId as the foreign key using [key, foreign key] attribute.
Also, note that Property and Address entities are inheriting from FullAuditedEntity, which imposes int Id as the primary key as well.
When I try to run the database migration, it throws the following error:
"Multiple identity columns specified for table 'IpProperties'. Only one identity column per table is allowed."
I believe this is happening because I am specifying PropertyId as the primary key on Property entity, where it already has Id as the primary key. If I do not specify that, then I will have to use Id as the "key, foreign key" value in Address table, which then would conflict with Address table's Id field.
How should I go about coding one to one relationship when there's the Id constraint being imposed by FullAuditedEntity, and EF wants to use the PK as the FK also?
Thanks in advance for your help!
Here's the section of the code:
[Table("IpProperties")] public class Property : FullAuditedEntity {
[Key]
public virtual int PropertyId { get; set; }
public virtual bool Vacant { get; set; }
public virtual Address Address { get; set; }
}
[Table("IpAddresses")] public class Address : FullAuditedEntity {
[Key, ForeignKey("Property")]
public virtual int PropertyId { get; set; }
[Required]
[MaxLength(MaxLength)]
public virtual string StreetNumber { get; set; }
public virtual Property Property { get; set; }
}