我在数据库中有一个enity。我想创建现有实体的3个副本,仅在创建日期属性中更改。 怎么做到这一点?
我用AsNoTracking加载了enity。并尝试在for循环中创建。但我只得到一个项目添加到db。
using(var database = new MyDbContext()) {
MyModel myModel = database.Where(m => m.SomeProperty == someValue).AsNoTracking();
for(int i=0;i<5;i++)
{
myModel.SomeOtherProperty = someOtherValue; //user changed a value
database.MyModels.Add(myModel);
}
database.SaveChanges();
}
由于
答案 0 :(得分:0)
好的,这就是它的完成方式。为表创建DDL:
USE [Breaz] --Your database name here
GO
/****** Object: Table [dbo].[CopyCloneTable] Script Date: 12/29/2016 11:15:23 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CopyCloneTable](
[Id] [int] IDENTITY(1,1) NOT NULL,
[PropertyToCopy] [varchar](10) NULL,
[SomeOtherProperty] [varchar](10) NULL,
CONSTRAINT [PK_CopyCloneTable] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
添加一行:
/****** Script for SelectTopNRows command from SSMS ******/
--USE your db name instead of Breaz here
INSERT INTO [Breaz].[dbo].[CopyCloneTable] ([PropertyToCopy], [SomeOtherProperty])
VALUES ('copyme', -1)
右键单击您的项目并添加ADO.NET实体数据模型,将其命名为MyDb,并使用名为MyDbContext的连接添加您的表
以下是您的观点:
public ActionResult Index9() //this Method name can change
{
using (var database = new MyDbContext())
{
CopyCloneTable myModel = database.CopyCloneTables.Where(m => m.SomeOtherProperty
== "-1").FirstOrDefault();
for (int i = 0; i < 3; i++)
{
database.CopyCloneTables.Add(new CopyCloneTable
{
PropertyToCopy = myModel.PropertyToCopy,
SomeOtherProperty = i.ToString()
});
}
database.SaveChanges();
}
return View();
}