Maybe the title is misunderstood but I'm gonna try to explain my situation here.
So, considering my entity Person
that has a virtual property Country
, as follow:
public class Person {
public long Id { get; set;}
public short IdCountry { get; set;}
public virtual Country Country { get; set; }
...
}
and the mapping as follow:
...
builder.HasOne(c => c.Country)
.WithMany()
.HasForeignKey(c => c.IdCountry);
and my repository is generic.
What happens here is, when I try to save some change in Person
, the Country
entity state came to me as Added
wich does not make sense.
I'm exposing here a similar example that what is happening to me. Actually, I have like five others virtual properties in my class Person
and some of them are in this state (Added
).
Has anyone ever dealt with it before? Thanks in advance.
EDIT: Ansewing @alans reply: I'm doing something similar as follow:
foreach (var entrie in entry.Context.ChangeTracker.Entries())
{
try
{
key = entrie.Entity.GetType().GetProperty("Id").GetValue(entrie.Entity, null);
}
catch (Exception ex)
{
key = null;
}
if (key != null && entrie.State == EntityState.Added)
{
entrie.State = EntityState.Unchanged;
}
else if (Convert.ChangeType(key, typeof(long)) as long? == 0)
{
entrie.State = EntityState.Added;
}
}
_dbContext.SaveChanges();
@TanvirArjel this method above is where the state come as Added
I was using AsNoTracking()
extension method for performance questions in EF6 but I realized that in EFCore this particular method is a little bit different (I was migrating the code). So, I only removed the method
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments