EF一对一和一对多的一个例子

时间:2021-09-06 11:55:09

创建数据表和测试数据:

create table Orders
(
 OrderId int primary key identity(1,1),
 OrderNo nvarchar(30),
 TotalAmount decimal(10,2),
 OrderTime datetime default getdate()
)
create table OrderDetails
(
    OrderDetailId int primary key identity(1,1),
    OrderId int,
    ProductId int,
    ProductName nvarchar(30),
    AddTime datetime default getdate()
)
create table Products
(
    ProductId int primary key identity(1,1),
    Name nvarchar(30),
)


insert into Orders(OrderNo,TotalAmount) values('001',500);
insert into Orders(OrderNo,TotalAmount) values('002',800);
insert into Orders(OrderNo,TotalAmount) values('003',1000);
insert into Orders(OrderNo,TotalAmount) values('004',560);
insert into Orders(OrderNo,TotalAmount) values('005',900);

insert into OrderDetails(OrderId,ProductId,ProductName) values(1,1,'Iphone8');
insert into OrderDetails(OrderId,ProductId,ProductName) values(1,2,'MI6');
insert into OrderDetails(OrderId,ProductId,ProductName) values(2,3,'HW7');
insert into OrderDetails(OrderId,ProductId,ProductName) values(3,4,'MZ');

insert into Products(Name) values('Iphone8');
insert into Products(Name) values('MI6');
insert into Products(Name) values('HW7');
insert into Products(Name) values('MZ');

select * from Orders
select * from OrderDetails
select * from Products

 

创建DbContext和实体类:

public class OrderManamgerDBContext : DbContext
    {
        public DbSet<Orders> Orders { get; set; }
        public DbSet<OrderDetails> OrderDetails { get; set; }
        public DbSet<Products> Products { get; set; }

        public OrderManamgerDBContext() { }
        public OrderManamgerDBContext(string connectionString) : base(connectionString) { }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new OrdersConfiguration());
            modelBuilder.Configurations.Add(new OrderDetailsConfiguration());
            modelBuilder.Configurations.Add(new ProductsConfiguration());
            
            base.OnModelCreating(modelBuilder);
        }
    }

    public class OrdersConfiguration : EntityTypeConfiguration<Orders>
    {
        public OrdersConfiguration()
        {
            HasKey(od => od.OrderID);
        }
    }
    public class OrderDetailsConfiguration : EntityTypeConfiguration<OrderDetails>
    {
        public OrderDetailsConfiguration()
        {
            //不是按照EF默认规则命名的需要手动映射
            //HasEntitySetName("OrderDetails");
            //Property(t => t.Orders_Id).HasColumnName("OrderId");

            HasKey(odt => odt.OrderDetailId);
        }
    }
    public class ProductsConfiguration : EntityTypeConfiguration<Products>
    {
        public ProductsConfiguration()
        {
            //不是按照EF默认规则命名的需要手动映射
            HasKey(p => p.ProductId);
        }
    }

    public class Orders
    {
        public int OrderID { get; set; }
        public string OrderNo { get; set; }
        public decimal TotalAmount { get; set; }
        public DateTime OrderTime { get; set; }
        public virtual List<OrderDetails> OrdersDetail { get; set; }//自动延迟加载需要virtual关键字,此为导航属性.
    }

    public class OrderDetails
    {
        public int OrderDetailId { get; set; }
        public int OrderID { get; set; }
        public int ProductID { get; set; }
        public string ProductName { get; set; }
        public DateTime AddTime { get; set; }
        public virtual Products Product { get; set; }
    }

    public class Products
    {
        public int ProductId { get; set; }
        public string Name { get; set; }
    }

 

创建数据库连接:

 <connectionStrings>
    <add name="DbContext" connectionString="Data Source=127.0.0.1;Initial Catalog=DBTest;User ID=sa;Password=sasa;Persist Security Info=True;" providerName="System.Data.SqlClient"/>
  </connectionStrings>

 

运行测试程序:

 class EFTest
    {
        static OrderManamgerDBContext odmdb = new OrderManamgerDBContext("DbContext");
        //static OrderManamgerDBContext odmdb = new OrderManamgerDBContext(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString);
        public static void Main(string[] args)
        {

            //var rlt = odmdb.Orders.Include("OrdersDetail").Where(od => od.OrderID == 1);//Eager Loading

            var rlt = odmdb.Orders.Where(od => od.OrderID == 1).ToList();//Lazy Loading:要用ToList方法,否则Foreach的时候不能加载

            //string sql = rlt.ToString();

            foreach(var itm in rlt)
            {
                Console.WriteLine("单据编号 "+itm.OrderNo );

                if (itm.OrdersDetail != null && itm.OrdersDetail.Count > 0)
                {
                    Console.WriteLine("明细产品:");
                    foreach (var citm in itm.OrdersDetail)
                    {
                        //Console.WriteLine(citm.ProductName);
                        //Console.WriteLine(citm.Product.Name);

                        //Explicti Loading
                        var p = odmdb.Entry(citm);
                        p.Reference(t => t.Product).Load();//加载单个对象
                        //od.Collection(t => t.OrdersDetail).Load();//加载集合
                        Console.WriteLine(citm.Product.Name);
                        
                    }
                }
                
            }

            
            Console.Read();
        }

    }