EF Code First一對一、一對多、多對多關聯關系配置


1、EF Code First一對一關聯關系

   項目結構圖:

  實體類:

  Account.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Northwind.App.Entities
{
   public class Account
    {
       /// <summary>
       /// 賬戶ID
       /// </summary>
       public int AccountID { get; set; }

       /// <summary>
       /// 賬戶名
       /// </summary>
       public string AccountName { get; set; }

       /// <summary>
       /// 密碼
       /// </summary>
       public string Password { get; set; }

       /// <summary>
       /// 用戶信息
       /// </summary>
       public virtual User User { get; set; }
    }
}

  User.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Northwind.App.Entities
{
   public class Account
    {
       /// <summary>
       /// 賬戶ID
       /// </summary>
       public int AccountID { get; set; }

       /// <summary>
       /// 賬戶名
       /// </summary>
       public string AccountName { get; set; }

       /// <summary>
       /// 密碼
       /// </summary>
       public string Password { get; set; }

       /// <summary>
       /// 用戶信息
       /// </summary>
       public virtual User User { get; set; }
    }
}

  實體映射類:

  AccountMap.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data.Entity.ModelConfiguration;
using System.ComponentModel.DataAnnotations.Schema;

using Northwind.App.Entities;

namespace Northwind.App.Mapping
{
    public class AccountMap : EntityTypeConfiguration<Account>
    {
        public AccountMap()
        {
            // Primary Key
            this.HasKey(t => t.AccountID);

            // Properties
            this.Property(t => t.AccountName).HasMaxLength(50);
            this.Property(t => t.Password).HasMaxLength(100);

            // Table & Column Mappings
            this.ToTable("Account");
            this.Property(t => t.AccountID).HasColumnName("AccountID");
            this.Property(t => t.AccountName).HasColumnName("AccountName");
            this.Property(t => t.Password).HasColumnName("Password");
        }
    }
}

  UserMap.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data.Entity.ModelConfiguration;
using System.ComponentModel.DataAnnotations.Schema;

using Northwind.App.Entities;

namespace Northwind.App.Mapping
{
    public class UserMap : EntityTypeConfiguration<User>
    {
        public UserMap()
        {
            // Primary Key
            this.HasKey(t => t.AccountID);

            // Properties
            this.Property(t => t.AccountID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
            this.Property(t => t.UserName).HasMaxLength(50);
            this.Property(t => t.Email).HasMaxLength(100);

            // Table & Column Mappings
            this.ToTable("User");
            this.Property(t => t.AccountID).HasColumnName("AccountID");
            this.Property(t => t.UserName).HasColumnName("UserName");
            this.Property(t => t.Email).HasColumnName("Email");
            this.Property(t => t.RegisterDate).HasColumnName("RegisterDate");

            // Relationships
            this.HasRequired(t => t.Account)
                .WithRequiredDependent(t => t.User);
        }
    }
}

  NorthwindContext.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data.Entity;

using Northwind.App.Entities;
using Northwind.App.Mapping;

namespace Northwind.App
{
    public class NorthwindContext : DbContext
    {
        static NorthwindContext()
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<NorthwindContext>());
        }

        public DbSet<Account> Accounts { get; set; }
        public DbSet<User> Users { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new AccountMap());
            modelBuilder.Configurations.Add(new UserMap());
        }
    }
}

  Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Northwind.App.Entities;

namespace Northwind.App
{
    class Program
    {
        static void Main(string[] args)
        {
            using (NorthwindContext db = new NorthwindContext())
            {
                Account account = new Account { AccountName = "Test", Password = "1" };
                db.Accounts.Add(account);

                User user = new User { AccountID = account.AccountID, UserName = "測試", Email = "test@126.com", RegisterDate = DateTime.Now };
                db.Users.Add(user);

                db.SaveChanges();
            }
        }
    }
}

  代碼運行后生成的數據庫結構圖:

 

2、EF Code First一對多關聯關系

  關聯表:Product 產品表、Category分類表

  關聯關系:一個產品屬於一個分類,一個分類可以有多個產品

  實體代碼:

  Category.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Northwind.App.Entities
{
    public class Category
    {
        /// <summary>
        /// 分類ID
        /// </summary>
        public Guid CategoryID { get; set; }

        /// <summary>
        /// 分類名稱
        /// </summary>
        public string CategoryName { get; set; }

        /// <summary>
        /// 產品
        /// </summary>
        public virtual ICollection<Product> Products { get; set; }
    }
}

  Product.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Northwind.App.Entities
{
    public class Product
    {
        /// <summary>
        /// 產品ID
        /// </summary>
        public Guid ProductID { get; set; }

        /// <summary>
        /// 產品名稱
        /// </summary>
        public string ProductName { get; set; }

        /// <summary>
        /// 單價
        /// </summary>
        public decimal UnitPrice { get; set; }

        /// <summary>
        /// 數量
        /// </summary>
        public Nullable<int> Quantity { get; set; }

        /// <summary>
        /// 庫存
        /// </summary>
        public Nullable<int> UnitsInStock { get; set; }

        /// <summary>
        /// 產品類別ID
        /// </summary>
        public Guid CategoryID { get; set; }

        /// <summary>
        /// 產品類別
        /// </summary>
        public virtual Category Category { get; set; }
    }
}

  實體映射類:

  CategoryMap.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data.Entity.ModelConfiguration;
using System.ComponentModel.DataAnnotations.Schema;

using Northwind.App.Entities;

namespace Northwind.App.Mapping
{
    public class CategoryMap : EntityTypeConfiguration<Category>
    {
        public CategoryMap()
        {
            // Primary Key
            this.HasKey(t => t.CategoryID);

            // Properties
            this.Property(t => t.CategoryID)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            this.Property(t => t.CategoryName).IsRequired()
                .HasMaxLength(100);

            // Table & Column Mappings
            this.ToTable("Category");
            this.Property(t => t.CategoryID).HasColumnName("CategoryID");
            this.Property(t => t.CategoryName).HasColumnName("CategoryName");
        }
    }
}

  ProductMap.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data.Entity.ModelConfiguration;
using System.ComponentModel.DataAnnotations.Schema;

using Northwind.App.Entities;

namespace Northwind.App.Mapping
{
    public class ProductMap : EntityTypeConfiguration<Product>
    {
        public ProductMap()
        {
            // Primary Key
            this.HasKey(t => t.ProductID);

            // Properties
            this.Property(t => t.ProductID)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            this.Property(t => t.ProductName).IsRequired()
                .HasMaxLength(100);
            this.Property(t => t.UnitPrice).HasPrecision(10, 2);

            // Table & Column Mappings
            this.ToTable("Product");
            this.Property(t => t.ProductID).HasColumnName("ProductID");
            this.Property(t => t.ProductName).HasColumnName("ProductName");
            this.Property(t => t.UnitPrice).HasColumnName("UnitPrice");
            this.Property(t => t.Quantity).HasColumnName("Quantity");
            this.Property(t => t.UnitsInStock).HasColumnName("UnitsInStock");
            this.Property(t => t.CategoryID).HasColumnName("CategoryID");

            // Relationships
            this.HasRequired(t => t.Category)
                .WithMany(t => t.Products)
                .HasForeignKey(t => t.CategoryID)
                .WillCascadeOnDelete(false);
        }
    }
}

  NorthwindContext.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data.Entity;

using Northwind.App.Entities;
using Northwind.App.Mapping;

namespace Northwind.App
{
    public class NorthwindContext : DbContext
    {
        static NorthwindContext()
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<NorthwindContext>());
        }

        public DbSet<Account> Accounts { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<Product> Products { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new AccountMap());
            modelBuilder.Configurations.Add(new UserMap());
            modelBuilder.Configurations.Add(new CategoryMap());
            modelBuilder.Configurations.Add(new ProductMap());
        }
    }
}

  Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Northwind.App.Entities;

namespace Northwind.App
{
    class Program
    {
        static void Main(string[] args)
        {
            using (NorthwindContext db = new NorthwindContext())
            {
                Category category = new Category { CategoryName = "手機數碼" };
                db.Categories.Add(category);

                Product product = new Product { CategoryID = category.CategoryID, ProductName = "IPhone5", UnitPrice = 5000m, Quantity = 100, UnitsInStock = 60 };
                db.Products.Add(product);

                db.SaveChanges();
            }
        }
    }
}

  運行代碼后生成的數據表:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM