文档章节

asp.net mvc code first实体关系一对一、一对多、多对多的设置方法

独坐苔痕但观罗敷
 独坐苔痕但观罗敷
发布于 2016/07/15 17:14
字数 935
阅读 21
收藏 0

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();
            }
        }
    }
}

复制代码

  运行代码后生成的数据表:

本文转载自:http://www.cnblogs.com/libingql/archive/2013/01/31/2888201.html

共有 人打赏支持
独坐苔痕但观罗敷
粉丝 0
博文 38
码字总数 11603
作品 0
宜宾
程序员
私信 提问
学习hibernate(五) -- hibernate映射关系

组合关系 在开发时,有一种情况,有一张数据表的数据来自于多个对象。比如,一个computer(电脑)表,其中有电脑的基本信息、CPU信息、显卡信息、主板信息和内存信息等等,对应的实体对象则是...

杰克鹏仔
2016/04/07
67
0
Hibernate 级联和关系维护

1、Hibernate中的级联操作: 在Hibernate中,针对持久化实体的配置文件中有Cascade这样一个属性,就是级联,也就是说在操作当前实体时,针对当前实体的操作会影响到相应配置的关联实体,比如...

Winnie007
2015/08/28
96
0
Hibernate之关联关系映射(一对多和多对一映射,多对多映射)

~接着之前的Hibernate框架接着学习(上篇面试过后发现真的需要学习一下框架了,不然又被忽悠让去培训。)~ 1:Hibernate的关联映射,存在一对多和多对一映射,多对多映射:   1.1:一对多和...

别叫小伙
2017/03/20
0
0
Hibernate框架学习之注解配置关系映射

上篇文章我们通过注解对映射了单个实体类,但是具体项目中往往实体类之间又是相互关联的,本篇文章就是从实体类之间存在的不同关联角度,具体学习下如何映射他们之间的关联,主要涉及内容如下...

Single_YAM
2017/11/15
0
0
Hibernate(三)——框架中的关系映射

在设计数据库时我们会考虑,表与表之间的关系,例如我们前边经常提到的一对一,一对多,多对多关系,在数据库中我们通过外键,第三张表等来实现这些关系。而Hibernate时间实体类和数据库中的...

凡尘里的一根葱
2015/11/11
0
0

没有更多内容

加载失败,请刷新页面

加载更多

Redis异构集群之间数据迁移方案

一、Redis集群迁移工具 最近在做Redis数据迁移,网上找了两款开源的Redis迁移工具。 第一种:redis-port Codis官方提供的一个工具,redis-port是一个Redis工具,通过解析rdb文件,实现Redis...

IT--小哥
12分钟前
1
0
MySQL5.7源码安装

5、MySQL源码安装(centos7.5) 5.1 下载软件 官方自带(boost版本mysql) wget https://dev.mysql.com/get/Downloads/MySQL-5.7/mysql-boost-5.7.20.tar.gz tar xf mysql-boost-5.7.20.tar.g......

hnairdb
16分钟前
1
0
解压zip包(zip4j)

1:引入zip4j_1.3.2.jar 2:源码如下: package test;import java.io.File;import java.io.IOException;import java.util.ArrayList;import java.util.List;import net.lingal......

uug
19分钟前
1
0
MySQL 8在CentOS 7用rpm安装

1.配置MySQL yum安装源和安装: #配置MySQL5.7的安装源 #https://repo.mysql.com/mysql57-community-release-el7.rpm #https://repo.mysql.com/mysql57-community-release-el7-11.noarch.rp......

MichaelShu
26分钟前
1
0
docker 安装zookeeper

1.下拉镜像: docker pull zookeeper 2.运行镜像: docker run --name myZookeeper --restart always -d zookeeper 此时,2181 2888 3888分别是zookeeper的(客户端端口,跟随端口,选择端口)...

狼王黄师傅
27分钟前
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部