我定义了以下类。当我调用DeleteProperty方法时,它给我一个错误。不知道我在想什么..
我正在使用EF代码优先方法来创建数据库中所需的架构。
数据库架构看起来不错。它创建了属性表和属性地址表,并且属性地址表以propertyId作为外键。当我通过UI添加属性对象时,属性记录已添加确定。但是,当我尝试从UI删除Property对象时,出现以下错误。
A relationship from the 'Property_PropertyAddress' AssociationSet is in the 'Deleted' state. Given multiplicity constraints, a corresponding 'Property_PropertyAddress_Target' must also in the 'Deleted' state.
任何帮助将不胜感激。
// base class
public abstract class BaseEntity
{
public int ID { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
}
// property class
public class Property : BaseEntity
{
// one to one relation with Property address
public virtual PropertyAddress PropertyAddress { get; set; }
// other properties....
}
public class PropertyMap : EntityTypeConfiguration<Property>
{
public PropertyMap()
{
// key
HasKey(t => t.ID);
// fields
Property(t => t.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(t => t.CreatedDate).IsRequired();
Property(t => t.ModifiedDate).IsRequired();
// other
// table name
ToTable("Property");
}
}
public class PropertyAddress :BaseEntity
{
public virtual Property Property { get; set; }
// other properties.....
}
public class PropertyAddressMap: EntityTypeConfiguration<PropertyAddress>
{
public PropertyAddressMap()
{
// key
HasKey(t => t.ID);
// fields
Property(t => t.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(t => t.CreatedDate).IsRequired();
Property(t => t.ModifiedDate).IsRequired();
// table name
ToTable("PropertyAddress");
HasRequired(t=>t.Property).WithRequiredDependent(p=>p.PropertyAddress).Map(m => m.MapKey("PropertyId")).WillCascadeOnDelete(true);
}
}
public int DeleteProperty(int id)
{
// get the property by id and then delete.
var property = GetProperty(id);
return repository.Delete(property);
}
Delete method in repository class:
public virtual int Delete<T>(T entity) where T : BaseEntity
{
// check for null argument
ThrowArgumentNullException(entity);
try
{
context.Set<T>().Remove(entity);
return context.SaveChanges();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}