public class User
{
public int ID { get; set; }
public string EmailAddress { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
public class Address
{
public int ID { get; set; }
public string City { get; set; }
public string Street { get; set; }
public string Postcode { get; set; }
}
class TestDbContext : DbContext
{
public TestDbContext()
: base("DefaultConnectionString")
{
}
public DbSet<User> Users { get; set; }
public DbSet<Address> Addresses { get; set; }
}
Above are the model definitions and DbContext difinitions. I want to add a new address for the user, so i wrote my code as bellow:
var context = new TestDbContext();
var user = context.Users.FirstOrDefault(item => item.ID == 1);
user.Addresses.Add(new Address()
{
City = "City",
Street = "Street",
Postcode = "Postcode",
});
context.SaveChanges();
My doubt is why there are 3 SQL queries are executed in this code?
It's generated in FirstOrDefault
SELECT TOP (1) [Extent1].[ID] AS [ID], [Extent1].[EmailAddress] AS [EmailAddress] FROM [dbo].[Users] AS [Extent1] WHERE 1 = [Extent1].[ID]
- It's generated in user.Addresses.Add
exec sp_executesql N'SELECT [Extent1].[ID] AS [ID], [Extent1].[City] AS [City], [Extent1].[Street] AS [Street], [Extent1].[Postcode] AS [Postcode], [Extent1].[User_ID] AS [User_ID] FROM [dbo].[Addresses] AS [Extent1] WHERE ([Extent1].[User_ID] IS NOT NULL) AND ([Extent1].[User_ID] = @EntityKeyValue1)',N'@EntityKeyValue1 int',@EntityKeyValue1=1
It's generated in SaveChanges
exec sp_executesql N'INSERT [dbo].[Addresses]([City], [Street], [Postcode], [User_ID]) VALUES (@0, @1, @2, @3) SELECT [ID] FROM [dbo].[Addresses] WHERE @@ROWCOUNT > 0 AND [ID] = scope_identity()',N'@0 nvarchar(max) ,@1 nvarchar(max) ,@2 nvarchar(max) ,@3 int',@0=N'City',@1=N'Street',@2=N'Postcode',@3=1
How can I avoid the second SQL?