MVC プロジェクトで (初めて) 注釈を付けてコードを作成しようとしています。
以下の POCO を作成しました。
[Table("Customers")]
public partial class Customer
{
public int Id { get; set; }
[Required]
[DisplayName("First Name")]
public string FirstName { get; set; }
[DisplayName("Last Name")]
[Required]
public string LastName { get; set; }
//other properties...
}
[Table("Vehicles")]
public partial class Vehicle
{
[Required]
public int Id { get; set; }
[Required]
public int CustomerId { get; set; }
[Required]
public string Make { get; set; }
[Required]
public string Model { get; set; }
[Required]
public string Year { get; set; }
//other fields
[ForeignKey("CustomerId")]
public virtual Customer Customer { get; set; }
}
[Table("CustomerAppointments")]
public partial class CustomerAppointment
{
[Key,Column(Order=0)]
public int CustomerId { get; set; }
[Key,Column(Order=1)]
public int VehicleId { get; set; }
public DateTime? AppointmentDate { get; set; }
public DateTime? AppointmentTime { get; set; }
public string AvailableDays { get; set; }
//other fields
[ForeignKey("CustomerId")]
public virtual Customer Customer { get; set; }
[ForeignKey("VehicleId")]
public virtual Vehicle Vehicle { get; set; }
}
ここでの私の意図はかなり明白だと思います。私には顧客がいます。それらの顧客は車を持っています。顧客と顧客の車両の 1 つがサービスのためにスケジュールされているテーブル CustomerAppointments を作成したいと考えています。
記録のために、これはモデル全体ではなく、質問のために単純化されています。
MvcScaffolding を使用して EF アイテムとビューを構築しています。
すべてがコンパイルされますが、顧客ページ (実際には、顧客を参照することは言及されていないクラス) に移動しようとすると、次のエラーが発生します...
Introducing FOREIGN KEY constraint 'FK_dbo.CustomerAppointments_dbo.Vehicles_VehicleId' on table 'CustomerAppointments' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
私はさまざまな注釈を試してみましたが、このようなもので流暢な API を使用しようとさえしました...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<CustomerAppointment>()
.HasRequired(ca => ca.Customer)
.WithRequiredPrincipal()
.WillCascadeOnDelete(false);
modelBuilder.Entity<CustomerAppointment>()
.HasRequired(ca => ca.Vehicle)
.WithRequiredPrincipal()
.WillCascadeOnDelete(false);
}
しかし、私はそれを機能させることができません。Google と SO で見つけたすべてのサンプルを読みましたが、役に立ちませんでした。
PS ...これが注釈のみで機能する場合、それが私の好みです。