Database Reference
In-Depth Information
In this example, we applied an Is Null condition on the Account entity that filters out rows that contain a
DeletedOn date/time. The code in Listing 2-20 demonstrates inserting into and retrieving rows from the Account table.
Listing 2-20. Inserting into and Retrieving from the Account
using (var context = new EF6RecipesContext())
{
context.Database.ExecuteSqlCommand(@"insert into chapter2.account
(DeletedOn,AccountHolderId) values ('2/10/2009',1728)");
var account = new Account { AccountHolderId = 2320 };
context.Accounts.Add(account);
account = new Account { AccountHolderId = 2502 };
context.Accounts.Add(account);
account = new Account { AccountHolderId = 2603 };
context.Accounts.Add(account);
context.SaveChanges();
}
using (var context = new EF6RecipesContext())
{
foreach (var account in context.Accounts)
{
Console.WriteLine("Account Id = {0}",
account.AccountHolderId.ToString());
}
}
In Listing 2-20, we use the ExecuteSqlCommand() method on the Database property of the DbContext to insert a
row into the database the old-fashioned way. We need to do this because we are inserting a row with a nonnull value
for the DeletedOn column. In our model, the Account entity type has no property mapping to this column; in fact, the
Account entity type would never be materialized with a row that had a DeletedOn value—and that's exactly what we
want to test.
The rest of the first part of the code creates and initializes three additional instances of the Account entity type.
These are saved to the database with the SaveChanges() method.
When we query the database, we should get only the three instances of the Account entity type that we added
with the SaveChanges() method. The row that we added using the ExecuteSqlCommand() method should not be
visible. The following output confirms it:
Account Id = 2320
Account Id = 2502
Account Id = 2603
 
Search WWH ::




Custom Search