EF实现主从表自动生成主键保存
Class cl = new Class() { ClassName = "一年级1班" }; TestDBEntities context = new TestDBEntities(); context.Class.Add(cl); Student st = new Student() { Class = cl, Name="wangxiaoming" }; context.Student.Add(st); context.SaveChanges();
下面给出数据库关系图
对应sql脚本:
CREATE TABLE [dbo].[Class]( [ClassID] [int] IDENTITY(1,1) NOT NULL, [ClassName] [nvarchar](50) NOT NULL, CONSTRAINT [PK_Class] PRIMARY KEY CLUSTERED ( [ClassID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
CREATE TABLE [dbo].[Student]( [StudentID] [int] IDENTITY(1,1) NOT NULL, [Name] [nvarchar](50) NOT NULL, [ClassID] [int] NOT NULL, CONSTRAINT [PK_Student] PRIMARY KEY CLUSTERED ( [StudentID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
设置class和student的主键和student的外键,并且主键为自增。