Giter VIP home page Giter VIP logo

Comments (6)

viniciusverasdossantos avatar viniciusverasdossantos commented on May 18, 2024

I have the following problem now:

The ObjectStateManager does not contain an ObjectStateEntry with a reference to an object of type 'Vvs.CPlusAnywhere.Dominio.Logistica.PedidosDeCompra.Pedidos.AtendimentoAoItemDoPedido'

public class AtendimentoAoItemDoPedido 
{
    public virtual ItemDoPedidoDeCompra ItemDoPedido { get; protected set; }
    public Guid IdItemDoPedido { get; protected set; }

    public virtual ItemDaEntrada ItemDaEntrada { get; protected set; }
    public Guid IdItemDaEntrada { get; protected set; }
    public decimal Quantidade { get; set; }

}

public class AtendimentoAoItemDoPedidoDbMap : EntityTypeConfiguration<AtendimentoAoItemDoPedido>
{

    public AtendimentoAoItemDoPedidoDbMap()
    {

        HasKey(a => new { a.IdItemDoPedido, a.IdItemDaEntrada });

        HasRequired(a => a.ItemDoPedido)
            .WithMany(i => i.Atendimentos)
            .HasForeignKey(a => a.IdItemDoPedido)
            .WillCascadeOnDelete(false);

        HasRequired(a => a.ItemDaEntrada)
            .WithMany(i => i.PedidosAtendidos)
            .HasForeignKey(a => a.IdItemDaEntrada)
            .WillCascadeOnDelete(false);

        Property(a => a.Quantidade).IsRequired();
    }

} 

        _mainUnitOfWork.BulkInsert(registros, b =>
        {
            b.BatchSize = 500000;
            b.BatchTimeout = 10000;
            b.SqlBulkCopyOptions = SqlBulkCopyOptions.KeepIdentity;                
        });

from entityframework-extensions.

 avatar commented on May 18, 2024

Can you provide the full stack trace and a more complete example of this issue? We will try to fix it ASAP.

We added a custom class for “ItemDoPedidoDeCompra” and “ItemDaEntrada” but everything worked. So again, there is a little thing we are missing to reproduce the issue.

Best Regards,

Jonathan

from entityframework-extensions.

 avatar commented on May 18, 2024

Closing: No answer

from entityframework-extensions.

AshishMoradiya avatar AshishMoradiya commented on May 18, 2024

I am facing similar problem like this The ObjectStateManager does not contain an ObjectStateEntry with a reference to an object of type 'sfSync.Product2'.

Product2.cs

public partial class Product2
{
	public Product2()
	{
		this.ActivityHistories = new HashSet<ActivityHistory>();
		this.Assets = new HashSet<Asset>();
		this.AttachedContentDocuments = new HashSet<AttachedContentDocument>();
		this.Attachments = new HashSet<Attachment>();
		this.CombinedAttachments = new HashSet<CombinedAttachment>();
		this.ContentDocumentLinks = new HashSet<ContentDocumentLink>();
		this.ContentVersions = new HashSet<ContentVersion>();
		this.EmailMessages = new HashSet<EmailMessage>();
		this.EntitySubscriptions = new HashSet<EntitySubscription>();
		this.Events = new HashSet<Event>();
		this.FeedItems = new HashSet<FeedItem>();
		this.LookedUpFromActivities = new HashSet<LookedUpFromActivity>();
		this.Notes = new HashSet<Note>();
		this.NoteAndAttachments = new HashSet<NoteAndAttachment>();
		this.OpenActivities = new HashSet<OpenActivity>();
		this.OpportunityLineItems = new HashSet<OpportunityLineItem>();
		this.PricebookEntries = new HashSet<PricebookEntry>();
		this.ProcessInstances = new HashSet<ProcessInstance>();
		this.ProcessInstanceHistories = new HashSet<ProcessInstanceHistory>();
		this.Product2Feed = new HashSet<Product2Feed>();
		this.Product2History = new HashSet<Product2History>();
		this.Tasks = new HashSet<Task>();
	}

	public string Id { get; set; }
	public string Name { get; set; }
	public string ProductCode { get; set; }
	public string Description { get; set; }
	public bool IsActive { get; set; }
	public System.DateTime CreatedDate { get; set; }
	public string CreatedById { get; set; }
	public System.DateTime LastModifiedDate { get; set; }
	public string LastModifiedById { get; set; }
	public System.DateTime SystemModstamp { get; set; }
	public string Family { get; set; }
	public bool IsDeleted { get; set; }
	public Nullable<System.DateTime> LastViewedDate { get; set; }
	public Nullable<System.DateTime> LastReferencedDate { get; set; }

	public virtual ICollection<ActivityHistory> ActivityHistories { get; set; }
	public virtual ICollection<Asset> Assets { get; set; }
	public virtual ICollection<AttachedContentDocument> AttachedContentDocuments { get; set; }
	public virtual ICollection<Attachment> Attachments { get; set; }
	public virtual ICollection<CombinedAttachment> CombinedAttachments { get; set; }
	public virtual ICollection<ContentDocumentLink> ContentDocumentLinks { get; set; }
	public virtual ICollection<ContentVersion> ContentVersions { get; set; }
	public virtual ICollection<EmailMessage> EmailMessages { get; set; }
	public virtual ICollection<EntitySubscription> EntitySubscriptions { get; set; }
	public virtual ICollection<Event> Events { get; set; }
	public virtual ICollection<FeedItem> FeedItems { get; set; }
	public virtual ICollection<LookedUpFromActivity> LookedUpFromActivities { get; set; }
	public virtual ICollection<Note> Notes { get; set; }
	public virtual ICollection<NoteAndAttachment> NoteAndAttachments { get; set; }
	public virtual ICollection<OpenActivity> OpenActivities { get; set; }
	public virtual ICollection<OpportunityLineItem> OpportunityLineItems { get; set; }
	public virtual ICollection<PricebookEntry> PricebookEntries { get; set; }
	public virtual ICollection<ProcessInstance> ProcessInstances { get; set; }
	public virtual ICollection<ProcessInstanceHistory> ProcessInstanceHistories { get; set; }
	public virtual User User { get; set; }
	public virtual User User1 { get; set; }
	public virtual ICollection<Product2Feed> Product2Feed { get; set; }
	public virtual ICollection<Product2History> Product2History { get; set; }
	public virtual ICollection<Task> Tasks { get; set; }
}

Bulkinsert code

static void FetchAndSaveAllRecords<T>(DbSet<T> sourceEntity, DbContext source, DbSet<T> destinationEntity, DbContext destination) where T : class
{
	var productList = new List<Product2>();
	var productsQuery = sourceEntity.AsNoTracking().ToList();
	productsQuery.ForEach(p => productList.Add((Product2)p.CloneObject<Product2>()));
	destination.BulkInsert(productList);
	destination.BulkSaveChanges();
}

I have common model for two dbContexes so cloning instances to avoid attaching and detaching

CloneObject code

static class ObjectExtension
{
	public static object CloneObject<T>(this object objSource) where T : new()
	{
		//Get the type of source object and create a new instance of that type
		//Type typeSource = typeof(T);
		object objTarget = new T(); // Activator.CreateInstance(typeSource);
		//Get all the properties of source object type
		PropertyInfo[] propertyInfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.NonPublic); // | BindingFlags.NonPublic | BindingFlags.Instance);
		//Assign all source property to taget object 's properties
		foreach (PropertyInfo property in propertyInfo)
		{
			//Check whether property can be written to
			if (property.CanWrite)
			{
				//check whether property type is value type, enum or string type
				if (property.PropertyType.IsValueType || property.PropertyType.IsEnum || property.PropertyType.Equals(typeof(System.String)))
				{
					property.SetValue(objTarget, property.GetValue(objSource, null), null);
				}
				//else property type is object/complex types, so need to recursively call this method until the end of the tree is reached
				else
				{
					//object objPropertyValue = property.GetValue(objSource, null);
					//if (objPropertyValue == null)
					//{
					//    property.SetValue(objTarget, null, null);
					//}
					//else
					//{
					//    property.SetValue(objTarget, objPropertyValue.CloneObject(), null);
					//}
				}
			}
		}
		return objTarget;
	}
}

Here is full stack trace of exception
at System.Data.Entity.Core.Objects.ObjectStateManager.GetObjectStateEntry(Object entity) at . . [ ](DbContext , List1 , , SchemaEntityType , Int32 , List1 , Boolean ) at DbContextExtensions. . ( ) at . . () at . . () at . . () at System.Data.SqlClient.SqlBulkCopy.ReadFromRowSource() at System.Data.SqlClient.SqlBulkCopy.ReadFromRowSourceAsync(CancellationToken cts) at System.Data.SqlClient.SqlBulkCopy.WriteToServerInternalAsync(CancellationToken ctoken) at System.Data.SqlClient.SqlBulkCopy.WriteRowSourceToServerAsync(Int32 columnCount, CancellationToken ctoken) at System.Data.SqlClient.SqlBulkCopy.WriteToServer(IDataReader reader) at . . (SqlTransaction , SqlConnection , , ) at . . ( ) at . . ( ) at . . (List1 )
at . . (List1 ) at . . (BulkOperation ) at Z.BulkOperations.BulkOperation.BulkInsert() at Z.EntityFramework.Extensions.EntityBulkOperation1.BulkInsert()
at . . [ ](BulkOperation1 , DbContext , List1 , Boolean , List1 , Type , String ) at . . . (SchemaEntityType ) at System.Collections.Generic.List1.ForEach(Action1 action) at . . [ ](DbContext , BulkOperation1 , IEnumerable1 , List1 )
at . . [ ](BulkOperation1 , DbContext , IEnumerable1 , List1 ) at DbContextExtensions.BulkInsert[T](DbContext this, IEnumerable1 entities, Action1 bulkOperationFactory) at DbContextExtensions.BulkInsert[T](DbContext this, IEnumerable1 entities)
at sfSync.Program.FetchAndSaveAllRecords[T](DbSet1 sourceEntity, DbContext source, DbSet1 destinationEntity, DbContext destination) in C:\Users\Administrator\documents\visual studio 2015\Projects\sfSync\sfSync\Program.cs:line 54
at sfSync.Program.SyncEntity[T](DbSet1 sourceEntity, DbContext source, DbSet1 destinationEntity, DbContext destination, Func2 func1) in C:\Users\Administrator\documents\visual studio 2015\Projects\sfSync\sfSync\Program.cs:line 35 at sfSync.Program.Main(String[] args) in C:\Users\Administrator\documents\visual studio 2015\Projects\sfSync\sfSync\Program.cs:line 25 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart()

from entityframework-extensions.

JonathanMagnan avatar JonathanMagnan commented on May 18, 2024

Hello @Ashish225 ,

This issue is normally caused when the reference from two entity is not clear enough. We will this month re-write our documentation, I will make sure to add an example for this case.

Since you add entities with child, I recommend you using AddRange with BulkSaveChanges instead

Example:

destination.AddRange(productList);
destination.BulkSaveChanges();

Let me know if it's now working with this method.

Note: You don't have to call BulkSaveChanges after calling BulkInsert

from entityframework-extensions.

AshishMoradiya avatar AshishMoradiya commented on May 18, 2024

Hello Jonathan,

Thanks for your reply. Here which AddRange() method you talking about, because here you are using it with destination object which is of type DbContext. So, there is no AddRange() method there in destination. but if you are talking for destinationEntity which is of type DbSet.
in that case I can't use AddRange() it with too as I will have code like below

 static void FetchAndSaveAllRecords<T>(DbSet<T> sourceEntity, DbContext source, DbSet<T> destinationEntity, DbContext destination) where T : class
        {
            var productList = new List<T>();
            var productsQuery = sourceEntity.AsNoTracking().ToList();
            productsQuery.ForEach(p => productList.Add((T)p.CloneObject()));

            destinationEntity.AddRange(productList);
            destination.BulkSaveChanges();
        }

that is perfectly working.

from entityframework-extensions.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.