我有以下存储库方法,主要做两件事: -
创建技术记录(父记录),并为其生成系统生成的ID。
然后创建一个子记录,其ID等于系统生成的TechnologyID,如下所示: -
public void InsertOrUpdateServer(TServer server....)
{
if (server.TServerID == default(int))
{
// New entity
var resource = entities.Resources.SingleOrDefault(a => a.RESOURCEID == assetid);
int technologyypeID = GetTechnologyTypeID("Server");
Int64 max =GetTagMaximumeNumber(technologyypeID);
Technology technology = new Technology
{
StartDate = DateTime.Now,
//code goes here...
};
entities.Technologies.Add(technology);
//code goes here
server.TServerID= technology.TechnologyID;// This what makes me confused!!!!!
entities.TServers.Add(server);
technology.IsDeleted = false;
technology.IsCompleted = true;
}
entities.SaveChanges();
但EF如何获取技术ID并将其分配给ServerID,因为当我第一次定义技术时,在我调用savechanges()方法之前没有生成ID,该方法实际创建了技术对象并获得了它的价值。所以首先我期待server.TServerID
获得0的值,但似乎代码将运行良好。所以,有人可以这样做吗?
我检查了sql profiler,它显示了以下2个插入操作: -
exec sp_executesql N'insert [dbo].[Technology]([Tag], [IsDeleted], [TypeID], [StartDate], [IT360ID], [IsCompleted], [PartialTag], [IsManaged])
values (@0, @1, @2, @3, @4, @5, @6, @7)
select [TechnologyID], [timestamp]
from [dbo].[Technology]
where @@ROWCOUNT > 0 and [TechnologyID] = scope_identity()',N'@0 nvarchar(50),@1 bit,@2 int,@3 datetime2(7),@4 bigint,@5 bit,@6 bigint,@7 bit',@0=N'H10020789904',@1=0,@2=2,@3='2014-12-20 00:55:43.1567755',@4=47404,@5=1,@6=10020789904,@7=0
exec sp_executesql N'insert [dbo].[TServers]([TServerID], [ServerModelID], [ILOIP], [RackID], [StatusID], [BackUpStatusID], [RoleID], [OperatingSystemID], [VirtualCenterID], [Comment], [IT360SiteID])
values (@0, @1, null, null, null, null, @2, null, null, null, @3)
select [timestamp]
from [dbo].[TServers]
where @@ROWCOUNT > 0 and [TServerID] = @0',N'@0 int,@1 int,@2 int,@3 bigint',@0=1510,@1=2,@2=3,@3=2102