The following code gives a rush tour of the Entity Framework 2.0.
It is by no means a complete guide. The EF has a lot of power and a lot of complexity but this post is meant as a getting started right away guide.
It demonstrates adding/insert records, different ways of adding records with foreign keys, querying the database, and at last deleting data.
Here is the schema:
Instantiate the context
using (Test2Entities context = new Test2Entities())
{
Car, User, Fleetcard, Address is a table represented by an entity object generated by the Entity Framework.
Car c1 = new Car { CarName = "Volvo" };
context.AddToCars(c1);
context.SaveChanges();
User u1 = new User { FirstName = "Donald", LastName =
context.AddToUsers(u1);
context.SaveChanges();
FleetCard ca1 = new FleetCard { FleetCardName = "Visa" };
context.AddToFleetCards(ca1);
context.SaveChanges();
Address a1 = new Address { Address1 = "Hove Blvd",AddressName = "VIP" };
context.AddToAddresses(a1);
context.SaveChanges();
List<User> s1 = (from x in context.Users where
x.UserName == "dduck" select x).ToList();
List<Address> s2 = (from x in context.Addresses where
x.AddressName == "VIP" select x).ToList();
Lets pretend we did not just create the objects, and we wish to create a UserAddress object. This table has foreign keys to a user and an address. So lets get a user and get an Address
Then we can create the object and save it
if (s1 != null && s2 != null && s1.Count > 0 && s2.Count > 0)
{
UserAddress ua1 = new UserAddress();
ua1.UserId = s1[0].UserId;
ua1.AddressId = s2[0].AddressId;
context.AddToUserAddresses(ua1);
context.SaveChanges();
}
Now you can have a more object oriented feel to the code by setting references instead
UserAddress ua1 = new UserAddress();
ua1.User = s1[0];
ua1.Address = s2[0];
System.Console.WriteLine("UserFleetCard
{0}:{1}:{2}:{3}", ufcc.UsersFleetCarId, ufcc.UserId, ufcc.CarId,
ufcc.FleetCardId);
System.Console.WriteLine("Card: {0}",
ufcc.FleetCard.FleetCardName);
System.Console.WriteLine("User: {0}", ufcc.User.UserName);
System.Console.WriteLine("Car: {0}", ufcc.Car.CarName);
EF does not have a direct way of deleting a bunch of records:
public static void DeleteWithEF()
{
using (Test2Entities context = new Test2Entities())
{
List<Car> cars = (from x in context.Cars select x).ToList();
cars.ForEach(x => context.Cars.DeleteObject(x));
context.SaveChanges();
}
Here I demonstrate displaying a record and its references records:
public static void DeleteAllGeneric(string tableName)
{
string sql = "Delete from " + tableName;
using (Test2Entities context = new Test2Entities())
{
context.ExecuteStoreCommand(sql);
}
Instead you can cheat and invoke a sql command directly
If you would like to see a full example, you can download a the full source code.
Some of the examples will make more sense in the context of the full source.
Note:The code relies on an entity model being present