石山浩

导航

EF 4.1 Code First Walkthrough 学习摘要

一个非常简单方便的 Entity Framework 初体验教程之一

原文from: http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-code-first-walkthrough.aspx


The easiest way to point Code First to an existing database is to add a App/Web.config connection string with the same name as your derived DbContext, for example:

<connectionStrings>
  <add 
    name="MyProductContext" 
    providerName="System.Data.SqlClient" 
    connectionString="Server=10.44.115.37;Database=Products;uid=salesUser;pwd=sellMoreProducts;"/>
</connectionStrings>

1. Install EF 4.1

    Manage NuGet Packages...
    Package Manager Console:
        PM> Install-Package EntityFramework

2. Create the Application

3. Create the Model

public class Category
{
    public string CategoryId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Product> Products { get; set; }
}

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public string CategoryId { get; set; }

    public virtual Category Category { get; set; }
}

4. Create a Context

    Add Reference: "EntityFramework 4.1";
    Add Reference: "System.Data.Entity 4.0";

using System.Data.Entity;

public class ProductContext : DbContext
{
    public DbSet<Category> Categories { get; set; }
    public DbSet<Product> Products { get; set; }
}

5. Reading & Writing Data

class Program
{
    static void Main(string[] args)
    {
        using (var db = new ProductContext())
        {
            // Add a food category 
            var food = new Category { CategoryId = "FOOD", Name = "Foods" };
            db.Categories.Add(food);
            int recordsAffected = db.SaveChanges();

            Console.WriteLine(
                "Saved {0} entities to the database, press any key to exit.",
                recordsAffected);

            Console.ReadKey();
        }
    }
}

6. Reading & Writing More Data

class Program
{
    static void Main(string[] args)
    {
        using (var db = new ProductContext())
        {
            // Use Find to locate the Food category 
            var food = db.Categories.Find("FOOD");
            if (food == null)
            {
                food = new Category { CategoryId = "FOOD", Name = "Foods" };
                db.Categories.Add(food);
            }

            // Create a new Food product 
            Console.Write("Please enter a name for a new food: ");
            var productName = Console.ReadLine();

            var product = new Product { Name = productName, Category = food };
            db.Products.Add(product);

            int recordsAffected = db.SaveChanges();

            Console.WriteLine(
                "Saved {0} entities to the database.",
                recordsAffected);

            // Query for all Food products using LINQ 
            var allFoods = from p in db.Products
                            where p.CategoryId == "FOOD"
                            orderby p.Name
                            select p;

            Console.WriteLine("All foods in database:");
            foreach (var item in allFoods)
            {
                Console.WriteLine(" - {0}", item.Name);
            }

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }
}

7. Setting an Initialization Strategy

    For the walkthrough we just want to drop and re-create the database whenever the model has changed, so at the top of the Main method in my Program class I’ve added the following code:

Database.SetInitializer<ProductContext>(new DropCreateDatabaseIfModelChanges<ProductContext>());

8. Data Annotations

    Ddd a supplier class to our model:

public class Supplier
{
    public string SupplierCode { get; set; }
    public string Name { get; set; }
}

    Add a set to our derived context:

public class ProductContext : DbContext
{
    public ProductContext()
    { }

    public DbSet<Category> Categories { get; set; }
    public DbSet<Product> Products { get; set; }
    public DbSet<Supplier> Suppliers { get; set; }
}

    Now if we ran our application we’d get an InvalidOperationException saying “EntityType 'Supplier' has no key defined.

    Add Reference: "System.ComponentModel.DataAnnotations 4.0";

    Annotate the SupplierCode property to identify that it is the primary key:

using System.ComponentModel.DataAnnotations;

public class Supplier
{
    [Key]
    public string SupplierCode { get; set; }
    public string Name { get; set; }
}

    The full list of annotations supported in EF 4.1 is:

  • KeyAttribute
  • StringLengthAttribute
  • MaxLengthAttribute
  • ConcurrencyCheckAttribute
  • RequiredAttribute
  • TimestampAttribute
  • ComplexTypeAttribute
  • ColumnAttribute
        Placed on a property to specify the column name, ordinal & data type
  • TableAttribute
        Placed on a class to specify the table name and schema
  • InversePropertyAttribute
        Placed on a navigation property to specify the property that represents the other end of a relationship
  • ForeignKeyAttribute
        Placed on a navigation property to specify the property that represents the foreign key of the relationship
  • DatabaseGeneratedAttribute
        Placed on a property to specify how the database generates a value for the property (Identity, Computed or None)
  • NotMappedAttribute
        Placed on a property or class to exclude it from the database

9. Fluent API

    To access the fluent API we override the OnModelCreating method in DbContext, in the following code we are using the fluent API to configure the Name property on Supplier to be required:

public class ProductContext : DbContext
{
    public ProductContext()
    { }

    public DbSet<Category> Categories { get; set; }
    public DbSet<Product> Products { get; set; }
    public DbSet<Supplier> Suppliers { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Supplier>()
            .Property(s => s.Name)
            .IsRequired();
    }
}

posted on 2012-11-28 22:32  石山浩  阅读(202)  评论(0编辑  收藏  举报