两个实体,其中一个实体单方面关联另一个实体,数据更新和添加。

    public class Products 
    {
        public int ID {get;set;}

        public string Name { get; set; }

        public ProductClass productClass { get; set; }
    }
    public class ProductClass
    {
        public int ID {get;set;}
    }
    public class ProductsMap : EntityTypeConfiguration<Products>
    {
        public ProductsMap()
        {
            this.ToTable("Pro_Products");

            this.HasRequired(p => p.productClass)
                .WithMany()
                .Map(p => p.MapKey("PCID"))
                .WillCascadeOnDelete(false);
        }
    }

Product单方面关联ProductClass。

更新代码:

        new public void Modify(Products entity)
        {
            using (var db = base.NewDB())
            {
                var old = db.Products.Single(p => p.ID == entity.ID);
                var oldPreproties = old.GetType().GetProperties();
                var newPreproties = entity.GetType().GetProperties();
                foreach (var olditem in oldPreproties)
                {
                    foreach (var item in newPreproties)
                    {
                        if (olditem.Name == item.Name)
                        {
                            olditem.SetValue(old, item.GetValue(entity));
                            break;
                        }
                    }
                }
                old.productClass = db.ProductClass.Single(p => p.ID == entity.productClass.ID);
               
                db.Entry(old).State = EntityState.Modified;
                db.SaveChanges();
            }
        }

记录下这个特殊的情况,以做后用

原文地址:https://www.cnblogs.com/FlyStupidBird/p/7073176.html