0

以前の質問の後、私はまだEF Code-Firstに苦労しています。

1 つのテーブルが他のテーブルにアクセスするために複数の Id を使用する 3 つ (この例では、実際にはもっとあります) があります。

2つの問題があります

1: データベースへの保存時に配送と配送の ID が設定されていません (「0」のまま)。2: DBMigrations を使用すると、RecordId のインデックスが 2 回作成されます。

.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();
      }

メインプログラム(2回目)

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 動作名を取得するには、キー フィールド 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 に答える