我正在开发一个 Entity Framework 5 Code First 项目。现在我无法创建错误:
"Cascading foreign key 'FK_dbo.DriverLicense_dbo.Person_PersonId' where the referencing column 'DriverLicense.PersonId' is an identity column.\r\nCould not create constraint
这些是我的实体,为什么我会收到该错误?我不是说 PersonId 是 DriverLicense 实体中的身份。
public class DriverLicense
{
public long DriverLicenseId { get; set; }
public long LicenseNumber { get; set; }
public long PersonId { get; set; }
public virtual Person Person { get; set; }
}
public class DriverLicenseMap : EntityTypeConfiguration<DriverLicense>
{
public DriverLicenseMap()
{
this.HasKey(t => t.DriverLicenseId);
// Table & Column Mappings
this.ToTable("DriverLicense");
this.Property(t => t.DriverLicenseId).HasColumnName("DriverLicenseId");
this.Property(t => t.LicenseNumber).HasColumnName("LicenseNumber");
this.Property(t => t.PersonId).HasColumnName("PersonId");
this.HasRequired(t => t.Person)
.WithMany(t => t.DriverLicenses)
.HasForeignKey(d => d.PersonId);
}
}
public class Person
{
public Person()
{
this.DriverLicenses = new List<DriverLicense>();
}
public long PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<DriverLicense> DriverLicenses { get; set; }
}
public class PersonMap : EntityTypeConfiguration<Person>
{
public PersonMap()
{
// Primary Key
this.HasKey(t => t.PersonId);
// Properties
this.Property(t => t.FirstName)
.IsRequired()
.HasMaxLength(50);
this.Property(t => t.LastName)
.IsRequired()
.HasMaxLength(50);
// Table & Column Mappings
this.ToTable("Person");
this.Property(t => t.PersonId).HasColumnName("PersonId");
this.Property(t => t.FirstName).HasColumnName("FirstName");
this.Property(t => t.LastName).HasColumnName("LastName");
}
提前致谢!吉列尔莫。
编辑:使用 SQL Profiler 我可以看到:
CREATE TABLE [dbo].[DriverLicense] (
[DriverLicenseId] [bigint] NOT NULL,
[LicenseNumber] [bigint] NOT NULL,
[PersonId] [bigint] NOT NULL IDENTITY,
CONSTRAINT [PK_dbo.DriverLicense] PRIMARY KEY ([DriverLicenseId])
)
我不明白为什么将 PersonId 创建为 Identity