ef设置非自增长id_EF6 CodeFirst My [Key] Id列不会自动递增,因为标识列应该是

博客围绕EF设置非自增长ID展开。作者定义了基类和派生类,在上下文配置中设置ID非自增长,测试时首次添加数据正常,再次添加出现重复键异常。最后给出解决方案,将ID属性设置为自增长选项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have several classes that I need to derive from a common base class which holds an Id. Ignoring the all but one of these for the moment, let's say we have:

public class MyBase {

[Key]

public int Id { get; set; }

}

public class MyName : MyBase {

public string Name { get; set; }

}

my context (DataContext) looks like this:

public DbSetMyNames { get; set; }

// to avoid having EF make a MyBases table and instead map

// MyBase.Id into MyNames and my other derived classes I do this ...

protected override void OnModelCreating((DbModelBuilder modelBuilder) {

modelBuilder.Entity()

.Property(c => c.Id)

.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

modelBuilder.Entity()

.Map(m => {

m.MapInheritedProperties();

m.ToTable("MyNames");

});

}

The resulting DB, when I Enable-Migrations, Add-Migration Initial, and Update-Database is that I get no table called MyBases, but instead I get the Id column in MyNames

dbo.MyNames

-----------

Id (PK, int, not null)

Name (nvarchar(max), null)

So far so good, all of that compiles and builds, and then I test it using something like the following:

using ( DataContext dc = new DataContext()) {

var jj = new MyName { Name = "Janice Joplin" };

dc.MyNames.Add(jj);

dc.SaveChanges();

var jh = new MyName { Name = "Jimmy Hendrix" };

dc.MyNames.Add(jh);

dc.SaveChanges();

}

This works the first time (Janice is added with Id = 0) but not the second ... Jimmy gets a DUPLICATE KEY exception. Note (for full disclosure) I'm actually creating the jj and jh objects in another part of my code, then passing them into this method (above) as MyBase objects, then casting them back to MyName objects if that's what they are. I hope that isn't a problem.

I guess if everything were in one table, the Id could be marked as Identity and @@IDENTITY could be used to assign the object Id value. Perhaps I will need to make a MyBases table after all, and create that record first, then duplicate the Id into the derived tables in a transaction. What's the best approach for this?

Any help for this EF6 CodeFirst newbie would be appreciated. THANKS.

解决方案

I remember when I used to do EF I would create a table with Identity and in the class I would attribute the id column with

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

so I am assuming that your code should be

modelBuilder.Entity()

.Property(c => c.Id)

.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值