在执行插入步骤时,我想在表上自动生成外键值。我尝试了NOTNULL Identity (1,1)
,但是它不起作用,我想插入一篇文章,并使用3个带有数据实体的自动生成的外键。
答案 0 :(得分:0)
这是您的课程...
干杯!
public partial class Meter
{
public int MeterId { get; set; } //<-- This is the IDENTITY
public string MeterNumber { get; set; }
public string MeterName { get; set; }
}
public MeterMap(DbModelBuilder modelBuilder) : EntityTypeConfiguration<Meter>
{
// Maps Table to Concrete Types
Map(m => m.MapInheritedProperties());
ToTable("Meter", "dbo")
.HasKey(m => m.MeterId);
Property(m => m.MeterId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
.IsRequired();
Property(m => m.MeterNumber)
.HasMaxLength(20)
.HasColumnType("varchar")
.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_Meter_AlternateKey", 1) { IsUnique = false }))
.IsOptional();
Property(m => m.MeterName)
.HasMaxLength(50)
.HasColumnType("varchar")
.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_Meter_AlternateKey", 2) { IsUnique = false }))
.IsOptional();
}
public class YourDbContext : DbContext
{
public YourDbContext() : base("Your.ConnectionString.Name")
{
Database.SetInitializer<YourDbContext>(null);
Database.CommandTimeout = WhatEverIntegerValueYouLike;
}
public virtual DbSet<Meter> Meter { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new MeterMap(modelBuilder));
}
}
public sealed class YourDbContextUnitOfWork : IUnitOfWork
{
#region <Constructors>
public YourDbContextUnitOfWork(YourDbContext dbContext)
{
DbContext = dbContext
}
public DbContext DbContext { get; set; }
[SetterProperty]
public ICompositeRepository<Meter> Meter { get; set; }
[DebuggerStepThrough]
public void Dispose()
{
// Free managed resources
if (DbContext != null)
DbContext.Dispose();
GC.SuppressFinalize(this);
}
[DebuggerStepThrough]
public void SubmitChanges()
{
DbContext.SaveChanges();
}
}