实体框架不会保存复杂的对象

时间:2013-05-09 22:13:37

标签: c# entity-framework poco

我基本上有以下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 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的Address,因为我创建了一个地址并直接在数据库中设置了它的Locale_LocaleID,然后我得到两组错误。 为什么已添加的地址导致此错误?

0 个答案:

没有答案