0

在较早的问题之后,我仍在努力使用 EF Code-First;

我有 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();
      }
4

1 回答 1

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; }
}
于 2013-05-07T04:07:05.227 回答