2

我基本上有以下 poco 课程

public class AddressType 
{ 
public Guid AddressTypeId;
public string TypeName;
}

public class Address
{
...

public virtual Guid AddressTypeID { get; set; }
public virtual AddressType AddressType { get; set; }
}

public class Locale
{
public virtual ICollection<Address> Addresses { get; set; }
}

在我的上下文中使用以下内容创建数据库

modelBuilder.Entity<Address>()
            .HasRequired(p => p.AddressType)
            .WithMany()
            .HasForeignKey( p => p.AddressTypeID)
            .WillCascadeOnDelete( false );

modelBuilder.Entity<AddressType>().HasKey(p => p.AddressTypeID);
        modelBuilder.Entity<AddressType>().Property(p => p.AddressTypeID)
           .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<AddressType>().Property(p => p.TypeName)
            .IsRequired()
            .HasMaxLength(32);

现在这一切对我来说都很好。这是问题所在。我可以创建一个区域设置,然后像这样向它添加一个地址

...

    Locale locale = iRepostory.Locales.Where( p => p.LocaleID == new Guid("xxxx")).SingleOrDefault();
    Address address = new Address();
    address.AddressTypeID = "xxxxx";
    address.AddressType = iRepository.AddressTypes.Where( p => p.AddressTypeID == "xxxx").SingleOrDefault();
    iRepository.SaveLocale(locale);

That works fine. 

Now if I attempt to add an additional address it fails
Locale locale = iRepostory.Locales.Where( p => p.LocaleID == new Guid("xxxx")).SingleOrDefault();
    Address address = new Address();
    address.AddressTypeID = "xxxxx";
    address.AddressType = iRepository.AddressTypes.Where( p => p.AddressTypeID == "xxxx").SingleOrDefault();
locale.Adresses.Add(address);
    iRepository.SaveLocale(locale);

It seems the error from the EntityValidationErrors
is
EntityValidationErrors.Entry.Entity.GetType().Name is AddressType
EntityValidationErrors.Entry.State is Added
then for that EntityValidateError.ValidationErrors
ValidationError.Property = TypeName

为什么我不能添加其他地址?
我知道错误来自已添加到区域设置的地址,因为我创建了一个地址并将其设置为 Locale_LocaleID 直接在数据库中,然后我得到两组错误。为什么已经添加的地址会导致此错误?

4

0 回答 0