public static bool IsItNew(BloggingContext context, Blog blog) => context.Blogs.Find(blog.BlogId) == null;
private static void IsItNew() { Console.WriteLine(); Console.WriteLine("Show entity-specific check for key set:"); using (var context = new BloggingContext()) { var blog = new Blog { Url = "http://sample.com" }; // Key is not set for a new entity Console.WriteLine($" Blog entity is {(IsItNew(blog) ? "new" : "existing")}."); context.Add(blog); context.SaveChanges(); // Key is now set Console.WriteLine($" Blog entity is {(IsItNew(blog) ? "new" : "existing")}."); } Console.WriteLine(); Console.WriteLine("Show general IsKeySet:"); using (var context = new BloggingContext()) { var blog = new Blog { Url = "http://sample.com" }; // Key is not set for a new entity Console.WriteLine($" Blog entity is {(IsItNew(context, (object)blog) ? "new" : "existing")}."); context.Add(blog); context.SaveChanges(); // Key is now set Console.WriteLine($" Blog entity is {(IsItNew(context, (object)blog) ? "new" : "existing")}."); } Console.WriteLine(); Console.WriteLine("Show key set on Add:"); using (var context = new BloggingContext()) { var blog = new Blog { Url = "http://sample.com" }; // Key is not set for a new entity Console.WriteLine($" Blog entity is {(IsItNew(context, (object)blog) ? "new" : "existing")}."); context.Add(blog); // Key is set as soon as Add assigns a key, even if it is temporary Console.WriteLine($" Blog entity is {(IsItNew(context, (object)blog) ? "new" : "existing")}."); } Console.WriteLine(); Console.WriteLine("Show using query to check for new entity:"); using (var context = new BloggingContext()) { var blog = new Blog { Url = "http://sample.com" }; Console.WriteLine($" Blog entity is {(IsItNew(context, blog) ? "new" : "existing")}."); context.Add(blog); context.SaveChanges(); Console.WriteLine($" Blog entity is {(IsItNew(context, blog) ? "new" : "existing")}."); } }