Comments (6)
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.
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.
Closing: No answer
from entityframework-extensions.
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 , List
1 , , 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 . . (List
1 )
at . . (List1 ) at . . (BulkOperation ) at Z.BulkOperations.BulkOperation.BulkInsert() at Z.EntityFramework.Extensions.EntityBulkOperation
1.BulkInsert()
at . . [ ](BulkOperation1 , DbContext , List
1 , Boolean , List1 , Type , String ) at . . . (SchemaEntityType ) at System.Collections.Generic.List
1.ForEach(Action1 action) at . . [ ](DbContext , BulkOperation
1 , IEnumerable1 , List
1 )
at . . [ ](BulkOperation1 , DbContext , IEnumerable
1 , List1 ) at DbContextExtensions.BulkInsert[T](DbContext this, IEnumerable
1 entities, Action1 bulkOperationFactory) at DbContextExtensions.BulkInsert[T](DbContext this, IEnumerable
1 entities)
at sfSync.Program.FetchAndSaveAllRecords[T](DbSet1 sourceEntity, DbContext source, DbSet
1 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, DbSet
1 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.
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.
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)
- ExecuteFutureAction (with useTransactions = true) swallows exceptions and can throw "The underlying provider failed on Rollback." exception HOT 2
- Npgsql.PostgresException: 23505: duplicate key value violates unique constraint HOT 6
- EF CORE 8 and Pgsql 8: Parameter without name in synchronize & merge HOT 3
- BulkInsert Error after upgrading to Ef Core .Net 8 with latest Extensions HOT 2
- BulkInsert Exception using NpgSql and jsonb in .NET 8 HOT 11
- Trial for EF core 7 HOT 3
- BulkInsert taking 20+ min for 80 000 data rows HOT 3
- Force output does not work for merge. HOT 3
- Invalid Cast. The update expression must be of type MemberInitExpression. HOT 3
- Bulk Operations for Postgres does not respect the PermanentTable setting HOT 2
- Avoid Prepared Statements for Bulk operations HOT 6
- WhereBulkContains throwing System.ArgumentNullException: 'Value cannot be null. (Parameter 'name')' HOT 15
- BulkUpdate and BulkMerge Do Not Apply Any Changes To The Table with Owned Entity HOT 1
- BulkSaveChanges results in Foreign Key Constraint Violation but SaveChanges works HOT 3
- BulkMerge is Causing Violation of PRIMARY KEY constraint HOT 1
- BulkInsert: System.IndexOutOfRangeException: 'There is no row at position 0.' HOT 4
- While inserting new record through BulkMerge it's not overriding default constraint value HOT 3
- The type initializer for 'Z.BulkOperations.LicenseManager' threw an exception HOT 13
- `PublicExtensions` static dictionaries are filling up HOT 4
- SQLite Invalid cast from 'System.String' to 'System.Guid' HOT 4
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from entityframework-extensions.