Please help to find the error.
Error text: One or more validation errors were detected during model generation. Because all of the properties in the dependent role are non-nullable, multiplicity of the principal role must be 1.
//File.cs
public class File
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Sp> Sps { get; set; }
}
//Sp.cs
public class Sp
{
public int Id { get; set; }
public int FileId { get; set; }
public File File { get; set; }
}
mapping code
//mapping File
class File : EntityTypeConfiguration<File>
{
public File()
{
ToTable("File", "dbo");
HasKey(x => x.Id);
Property(x => x.Id).HasColumnName("ID");
Property(x => x.Name).HasColumnName("NAME");
}
}
//mapping Sp
class Sp : EntityTypeConfiguration<Sp>
{
public Sp()
{
ToTable("Sp", "dbo");
HasKey(x => x.Id);
Property(x => x.Id).HasColumnName("ID");
Property(x => x.FileId).HasColumnName("FILE_ID");
//the location of the error
HasOptional(d => d.File)
.WithMany(d => d.Sps)
.HasForeingKey(d => d.FileId)
.WillCascadeOnDelete(false);
}
}
You have an optional foreign key mapped to a non nullable property which is contradictory, you need to go one way or the other.
Change HasOptional
to HasRequired
which means every Sp
must have an associated File
.
class Sp : EntityTypeConfiguration<Sp>
{
public Sp()
{
ToTable("Sp", "dbo");
HasKey(x => x.Id);
Property(x => x.Id).HasColumnName("ID");
Property(x => x.FileId).HasColumnName("FILE_ID");
//the location of the error
HasRequired(d => d.File)
.WithMany(d => d.Sps)
.HasForeingKey(d => d.FileId)
.WillCascadeOnDelete(false);
}
}
If this is not what you want then make FileID
nullable
public class Sp
{
public int Id { get; set; }
public int? FileId { get; set; }
public File File { get; set; }
}
Which will allow you to have Sp
records with no associated File
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.