2

私には2つのクラスがあり、1つは以下のようなコレクションプロパティです。

public class NotificationMessage
{
    public int ID { get; set; }
    public string Message { get; set; }
    public virtual ICollection<Device> Devices { get; set; }
}

public class Device
{
    public int ID  { get; set; }
    public string Token  { get; set; }
    public virtual ICollection<NotificationMessage> NotificationMessages { get; set; }
}

public class NotificationMessageDevice
{
    [Column(Order = 0), Key, ForeignKey("NotificationMessage")]
    public int NotificationMessageID { get; set; }

    [Column(Order = 1), Key, ForeignKey("Device")]
    public int DeviceID { get; set; }


    public virtual Device Device { get; set; }
    public virtual NotificationMessage NotificationMessage { get; set; }
}

上記のような関係を作成すると、エンティティ フレームワークは十分に賢く、NotificationMessageDevices を作成して、データベースに多対多の関係を作成します。

ここで問題が発生します。ここで、CreateDate をテーブル 'NotificationMessageDevices' に追加します。私が行ったことは、エンティティフレームワークが既存のデータベースにテーブル「NotificationMessageDevices」を作成する方法で「NotificationMessageDevice」という新しいクラスを作成したことです。新しいプロパティを追加し、Update-Verbose を呼び出しました。最初の例外は ID プロパティの欠落に関するもので、 public int ID {get;set;} を追加する必要がありましたが、これを追加すると、ID プロパティがインデックス プロパティであることがわかり、そのテーブル内のすべてのデータを削除する必要があります。

データ損失のないEntity Frameworkでのこのケースの回避策は何ですか:)

4

1 に答える 1

1

次のようにリンク エンティティを作成できます。

public class DeviceNotificationMessages
{
    public DeviceNotificationMessages()
    {
        CreateDate = DateTimeOffset.Now;
    }

    [Column(Order = 0), Key, ForeignKey("NotificationMessage")]
    public int NotificationMessageId { get; set; }
    public virtual NotificationMessage NotificationMessage { get; set; }
    [Column(Order = 1), Key, ForeignKey("Device")]
    public int DeviceID { get; set; }
    public virtual Device Device { get; set; }

    public DateTimeOffset CreateDate { get; set; }
}

その後、データの損失を避けるために、この新しいエンティティへの移行を自分で処理する必要があります。コード ファーストの移行を使用している場合は、手動移行を追加し (自動移行ではデータが失われます)、データが削除されないようにスクリプトを編集する必要があります。

于 2012-11-07T11:44:20.697 に答える