我有3个(在这个例子中,实际上有更多),其中1个表使用多个Id来访问其他表。
我有2个问题
1:保存到数据库时,未设置发货和交货的ID(保留为“0”)。 2:使用DBMigrations时,会为RecordId
创建两次索引.Index(t => t.RecordId),
.Index(t => t.RecordId);
代码示例:
记录类:
public class Record
{
public Record()
{
Shipping = new Shipping();
Delivery = new Delivery();
}
public int RecordId { get; set; }
public int ShippingId { get; set; }
public int DeliveryId { get; set; }
public virtual Shipping Shipping { get; set; }
public virtual Delivery Delivery { get; set; }
}
运输类:
public class Shipping
{
public int ShippingId { get; set; }
public string ShippingName { get; set; }
public virtual Record Record { get; set; }
}
交货等级:
public class Delivery
{
public int DeliveryId { get; set; }
public String DeliveryText { get; set; }
public virtual Record Record { get; set; }
}
上下文:
public class Context : DbContext
{
public DbSet<Record> Records { get; set; }
public DbSet<Shipping> Shippings { get; set; }
public DbSet<Delivery> Deliveries { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Record>()
.HasRequired(m => m.Shipping)
.WithRequiredDependent(x => x.Record)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Record>()
.HasRequired(m => m.Delivery)
.WithRequiredDependent(x => x.Record)
.WillCascadeOnDelete(false);
base.OnModelCreating(modelBuilder);
}
主程序(方法):
using (Context context = new Context())
{
var model = context.Records.Create();
var shipping = model.Shipping;
shipping.ShippingName = "TestContext";
var delivery = model.Delivery;
delivery.DeliveryText = "customText";
context.Entry(model).State = EntityState.Added;
context.SaveChanges();
}
主程序(第二次尝试)
using (Context context = new Context())
{
var model = context.Records.Create();
model.Shipping = context.Shippings.Create();
var shipping = model.Shipping;
shipping.ShippingName = "TestContext";
model.Delivery = context.Deliveries.Create();
var delivery = model.Delivery;
delivery.DeliveryText = "customText";
context.Entry(model).State = EntityState.Added;
context.SaveChanges();
}
答案 0 :(得分:0)
要避免额外索引,请不要在记录类中指定关键字段。 要获取默认标识行为名称,请键入字段Id
public class Record
{
public Record()
{
Shipping = new Shipping();
Delivery = new Delivery();
}
public int Id { get; set; }
public virtual Shipping Shipping { get; set; }
public virtual Delivery Delivery { get; set; }
}