Entity Framework, have I added this entry before?

I have a simple Entity.

public partial class Thing
{
    public Thing()
    {}

    public int Id { get; set; }
    public string Name { get; set; }
 }

I insert thousands of new records into the localDB database, but there will be only a few unique things. If I SaveChanges after each insertion, then it will work very slowly, but if I do not SaveChanges, then I can not determine if a new name newThing.Name exists. Or can I? I am pretty vaguely checking where something exists in the context of vs database vs pre / post SaveChanges. Can anyone clarify this for me?

Thing newThing = new Thing();
newThing.Name = "MyName";

context.Things.Add(d);

//returns null
Thing myFirstThing = context.Things.FirstOrDefault(c => c.Name == newThing.Name);

//returns false 
if (context.Detectors.Any(c => c.Name == newThing.Name))
{  //do some stuff}
+4
source share
1 answer

I think you can probably do this with ChangeTracker in your DbContext, BUT maybe it will be slow.

//(warning: free-handing this):
myContext.ChangeTracker.Entries<theEntityType>().Any(e => e.State == EntityState.Added && e.Entity.TheField == yourString);

, ( - , , ( ) 1000 )

< yourString, theEntity > . - O (1), , . , , .

0

All Articles