C# EF 依據資料新增或是更新原有資料
關鍵在於紅色底的字。 當有產品ID相符時,則更新產品,否則新增產品 Entities entities = new Entities(); List<ProductViewModel> products = ...; // 由外部帶入資料 foreach(ProductViewModel p in products){ Product tmp = new Product(); tmp.ID = p.ID ?? GUID,NewID().toString(); tmp.Name = p.Name; tmp.Code = p.Code; if (entities.Product.Any(x => x.ID == tmp .ID)) { entities.Product .Attach(tmp); entities.Entry(tmp).State = EntityState.Modified; } else { entities.Product .Add(tmp); } }