Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7634005
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T07:03:12+00:00 2026-05-31T07:03:12+00:00

I am using automapper to import from one DB into a new DB with

  • 0

I am using automapper to import from one DB into a new DB with a slightly different structure. I am not sure how to handle code tables such as TargetType below. Automapper seems to be creating duplicates when importing them(“Unable to determine the principal end of the ‘Models.ShipTarget_TargetType’ relationship. Multiple added entities may have the same primary key.” on db.SaveChanges()). I’ve also had the same problem with many to many relationships, but I don’t get the error there, because the bridge table allows AutoMapper to happily create the duplicates without violating any constraints.

In other words, when mapping a ShipTarget(there’s lots of these), when it maps the TargetType field(there’s only a few TargetTypes), it always creates a new TargetType, rather than checking whether it already exists in the destination and using the pre-existing instance. Since TargetType is a codes tables, I would want the same instance for a particular value shared across many ShipTargets.

Note that all the mapping is being done in one pass before save changes is called. So absolutely none of the TargetTypes exist in the destination database, so I expect it to create one of each from the source code table, but it is creating duplicates as if each ShipTarget is referencing a unique TargetType.

My current mapping is this(simplified, hopefully no typos):

var src2NewShip = Mapper.CreateMap<SourceDataModel.Ship, Ship>()
        .ForMember(newShp => newShp.Targets, c => c.MapFrom(srcShp => srcShp.ShipTargets));

var srcShipTargetType2NewTargetType = Mapper.CreateMap<SourceDataModel.ShipTargetType, TargetType>();

var srcShipTarget2SrcTarget = Mapper.CreateMap<SourceDataModel.ShipTarget, ShipTarget>()
          .ForMember(newTarget => newTarget.TargetType, c => c.MapFrom(srcTarget => srcTarget.ShipTargetType));

How do I ensure that it only creates as many TargetTypes as there are ShipTargetTypes in the source db? Instead of duplicating them when they are referenced by more than one ShipTarget.

This pseudo code expresses one idea I had to solve the problem, but this seems pretty convoluted and I’m not sure exactly how to get it working right anyhow:

var srcShipTarget2SrcTarget = Mapper.CreateMap<SourceDataModel.ShipTarget, ShipTarget>()
          .ForMember(newTarget => newTarget.TargetType, c => c.MapFrom(srcTarget => 
{
  newDb.Ships.SelectMany(s => s.ShipTargets).FirstOrDefault(st=>st.TargetType.UniqueName == srcTarget.UniqueName );
//here I would return the found instance, or call upon automapper to map srcTarget to a new TargetType and return that
//essentially, use existing, or return new
);


public class TargetType
  {
    [Key]
    public int TargetTypeKey { get; set; }

    public string UniqueName { get; set; }  
    ...  
  }

  public class ShipTarget
  {
    [Key]
    public int ShipTargetKey { get; set; }

    public int ShipKey { get; set; }
    [ForeignKey("ShipKey")]
    public Ship Ship { get; set; }

    public int TargetTypeKey { get; set; }
    [ForeignKey("TargetTypeKey")]
    public TargetType TargetType { get; set; }

    ...
  }

  public class Ship
  {
    [Key]
    public int ShipKey { get; set; }

    public virtual ICollection<ShipTarget> Targets { get; set; }
    ...
  }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T07:03:16+00:00Added an answer on May 31, 2026 at 7:03 am

    I wanted to do the below in the ConvertUsing of the TargetType so that it’d apply anywhere the code table was referenced, but I couldn’t figure out how to tell it to use a default mapping to create a new one if it didn’t exist, such as in the below where I do Mapper.Map(srcTarget.ShipTarget, newTarget.TargetType);

    So instead for the member of the class referencing the code table, I tell it to initially ignore that member, and then map it in an AfterMap by checking if the entry exists in the new code table, using that entry, and if it doesn’t exist then create a new one.

      var srcShipTarget2SrcTarget = Mapper.CreateMap<SourceDataModel.ShipTarget, ShipTarget>()
        .ForMember(newTarget => newTarget.TargetType, c => c.Ignore())
        .AfterMap((srcTarget, newTarget) =>
        {
          if (srcTarget.ProjectTargetType != null)
          {
            newTarget.TargetType = db.TargetTypes.FirstOrDefault(tt => tt.UniqueName == odsT.ProjectTargetType.UniqueName);
            if (newTarget.TargetType == null)
            {
              newTarget.TargetType = Mapper.Map(srcTarget.ShipTarget, newTarget.TargetType);
            }
          }
        });
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am using AutoMapper to datareader using code as discussed below http://elegantcode.com/2009/10/16/mapping-from-idatareaderidatarecord-with-automapper/ I see
I am using AutoMapper to map objects from a legacy database to a new
There are lots of tutorials for flattening domain models into DTO using AutoMapper. I
I have been using Automapper in our projects and just recently ran into an
I'm having a really difficult time mapping from a DynamicObject using Automapper -- the
Using Automapper, how do you handle the mapping of a property value on an
Hi I am using AutoMapper to move from a Model to a Dto and
I'm trying to ignore a property from my type when performing mapping using AutoMapper.
We are using AutoMapper from Codeplex and for me the destination object has all
I'm using AutoMapper which is a great tool. There's lots of examples converting from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.