csharp EF6 - 一对多

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp EF6 - 一对多相关的知识,希望对你有一定的参考价值。

namespace EntityFramework.Entity
{
    public class BaseEntity
    {
        public int Id { get; set; }
        public DateTime CreatedTime { get; set; }
        public DateTime ModifiedTime { get; set; }
    }
    
    public class Customer : BaseEntity
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public virtual  ICollection<Order> Orders { get; set; }
    }
    
    public class Order : BaseEntity
    {
        public byte Quantity { get; set; }
        public int Price { get; set; }
        public int CustomerId { get; set; }
        public virtual Customer Customer { get; set; }
    }
}

namespace EntityFramework.Map
{
    public class CustomerMap : EntityTypeConfiguration<Customer>
    {
        public CustomerMap()
        {
            // table
            ToTable("Customers");

            // key
            HasKey(t => t.Id);

            // properties
            Property(t => t.Name).HasColumnType("VARCHAR").HasMaxLength(50).IsRequired();
            Property(t => t.Email).HasColumnType("VARCHAR").HasMaxLength(50).IsRequired();
            Property(t => t.CreatedTime);
            Property(t => t.ModifiedTime);
        }
    }
	
    public class OrderMap : EntityTypeConfiguration<Order>
    {
        public OrderMap()
        {
            // table
            ToTable("Orders");

            // key
            HasKey(t => t.Id);

            // properties
            Property(t => t.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            Property(t => t.Quantity);
            Property(t => t.Price);
            Property(t => t.CustomerId);
            Property(t => t.CreatedTime);
            Property(t => t.ModifiedTime);

            // relationship
            HasRequired(t => t.Customer).WithMany(c => c.Orders)
                .HasForeignKey(t => t.CustomerId).WillCascadeOnDelete(false);
        }
    }
}

namespace EntityFramework
{
    public class EfDbContext : DbContext
    {
        public EfDbContext() : base("name=ConnectionString")
        {
            Database.SetInitializer(new CreateDatabaseIfNotExists<EfDbContext>());
        }

        public DbSet<Customer> Customers { get; set; }
        public DbSet<Order> Orders { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()
                .Where(type => !string.IsNullOrEmpty(type.Namespace))
                .Where(type => type.BaseType != null && type.BaseType.IsGenericType
                                                     && type.BaseType.GetGenericTypeDefinition() ==
                                                     typeof(EntityTypeConfiguration<>));

            foreach (var type in typesToRegister)
            {
                dynamic configurationInstance = Activator.CreateInstance(type);
                modelBuilder.Configurations.Add(configurationInstance);
            }

            base.OnModelCreating(modelBuilder);
        }
    }
	
    class Program
    {
        static void Main(string[] args)
        {
            using (var ctx = new EfDbContext())
            {
                ctx.Database.Log = Console.WriteLine;

                var customer = new Customer
                {
                    Name = "Jeffcky",
                    Email = "2517860965@qq.com",
                    CreatedTime = DateTime.Now,
                    ModifiedTime = DateTime.Now,
                    Orders = new List<Order>
                    {
                        new Order
                        {
                            Quantity = 12,
                            Price = 1500,
                            CreatedTime = DateTime.Now,
                            ModifiedTime = DateTime.Now
                        },
                        new Order
                        {
                            Quantity = 10,
                            Price = 2500,
                            CreatedTime = DateTime.Now,
                            ModifiedTime = DateTime.Now
                        }
                    }
                };
				
                ctx.Customers.Add(customer);
                ctx.SaveChanges();
            }
            Console.ReadKey();
        }
    }
}

以上是关于csharp EF6 - 一对多的主要内容,如果未能解决你的问题,请参考以下文章

csharp EF6 - 多对多第二种方式

csharp EF6 - 多对多第一种方式

csharp EF6.x |将SQL与代码相关联

代码第一个一对多自引用 WillCascadeOnDelete 错误

EF 代码第一个一对多(使用“通用”表)

EF 6 codde first - 一对多映射 - ICollection始终为null