我在客户和地址之间建立了一对一的关系。根据我的理解,我必须修改我拥有的OnModelCreating
方法。现在我已经准备好尝试我的应用程序了,但是我需要正确初始化我的数据库;但我遇到了一个错误。
主要计划是先创建一个客户,然后再创建一个与他们关联的地址。
这是我的上下文类:
public class VolumeV2Context : DbContext
{
public DbSet<GiftCard> GiftCards { get; set; }
public DbSet<Clients> Clients { get; set; }
public DbSet<Address> Address { get; set; }
// use if you need to drop the database
static VolumeV2Context(){
// use if need to reset the models
// Database.SetInitializer(new DropCreateDatabaseIfModelChanges<VolumeV2Context>());
// use to reset whole database tables
Database.SetInitializer(new DropCreateDatabaseAlways<VolumeV2Context>());
}
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Clients>()
.HasOptional(j => j.Address)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
modelBuilder.Entity<Address>()
.HasRequired(j => j.client)
.WithRequiredDependent()
.WillCascadeOnDelete(true) ;
base.OnModelCreating(modelBuilder);
}
}
楷模
public class Address
{
[Required]
public int Id { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Street Address")]
public string StreetAddress { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Postal Code")]
public string PostalCode { get; set; }
[DataType(DataType.Text)]
public string City {get; set; }
[DataType(DataType.Text)]
public string Province {get; set;}
public virtual Clients client { get; set; }
}
public class Clients
{
[Required]
public long Id { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
[DataType(DataType.PhoneNumber)]
[Display(Name = "Phone ")]
public string PhoneNumber { get; set; }
public virtual Address Address {get; set;}
[Display(Name = "Email List")]
public Boolean EmailList { get; set; }
[DataType(DataType.EmailAddress)]
[Display(Name = "E-mail")]
public string Email { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Hair Type")]
public string HairType { get; set; }
[DataType(DataType.MultilineText)]
public string Description { get; set; }
}
在我第一次调用数据库时,它在主索引方法中
return View(db.Clients.Take(25).ToList());
它返回一个错误说:
在表“地址”上引入 FOREIGN KEY 约束“FK_dbo.Addresses_dbo.Clients_client_Id”可能会导致循环或多个级联路径。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。无法创建约束。请参阅以前的错误。