Exception while evaluating EntityState of a List object in Entity Framework Core

.net asp.net-core c# entity-framework-6 entity-framework-core

Question

I am building a small logging application. In few scenarios, I am saving one TransactionHistory object by evaluating the EntityState. When a new object is added to DomainObject (TransactionHistory), the entity state is changed to added and SaveChanges() works fine.

public void LogTransactionHistory()
{
     var transactionsHistory = new TransactionsHistory();

     transactionsHistory.TransactionId = 1123;
     transactionsHistory.Status = 2;
     transactionsHistory.Comments = "Single Entity";

     context.TransactionsHistory.Add(transactionsHistory);

     if (context.Entry(transactionsHistory).State == EntityState.Added)
     {
         context.SaveChanges();
     }
}

And while saving a list of TransactionHistory objects and evaluating the EntityState, I get this exception:

The entity type 'List' was not found. Ensure that the entity type has been added to the model

This is my code:

public void LogHistoryList()
{
    var transactionHistoryList = new List<TransactionsHistory>();

    transactionHistoryList.Add(new TransactionsHistory()
            {
                TransactionId  = 50331,
                Status = 2,
                Comments = "Multiple entities",
            });

    context.TransactionsHistory.AddRange(transactionHistoryList );

    var addedEntities = context.ChangeTracker.Entries()
                .Where(x => x.State == EntityState.Added);

    // checking the entity state of transactionHistoryList
    if (context.Entry(transactionHistoryList).State == EntityState.Added) // exception
    {
        context.SaveChanges();
    }
}

Model:

public partial class TransactionsHistory
{
    public long TransactionId { get; set; }
    public short? Status { get; set; }
    public string Comments {get ;set;}
}

Can anyone help me with this issue? Am I missing anything?

Thanks in advance

1
0
4/10/2020 8:47:01 AM

Popular Answer

In this scenario you get all added entities from ChangeTracker in addedEntities and don't need to check again in if (context.Entry(transactionHistoryList).State == EntityState.Added).

context.Entry accept one entity but you pass the range of entities to context.Entry

You must change to this

context.TransactionsHistory.AddRange(transactionHistoryList);

var addedEntities = context.ChangeTracker.Entries()
                    .Any(x => x.State == EntityState.Added);

if (addedEntities)
{
    context.SaveChanges();
}

Update

if you want check all entities that are added, you can use this

foreach(var entity in ChangeTracker.Entries())
{
    if(entity.State = EntityState.Added)
    {
        //DoSomething
    }
}
0
4/10/2020 8:30:29 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow