首先是EF代码中的循环引用错误

时间:2011-10-03 12:43:54

标签: c# entity-framework-4.1 ef-code-first

这是我的抽象基类:

public abstract class ServiceStation
    {
        #region '----- Member(s) -----'

        public int Id { get; set; }

        public int CompanyId { get; set; }

        [ForeignKey("CompanyId")]
        public virtual Company Company { get; set; }

        public int GasolineBrandId { get; set; }

        [ForeignKey("GasolineBrandId")]
        public virtual GasolineBrand GasolineBrand { get; set; }

        [ForeignKey("LastUpdatedByUserId")]
        public virtual User LastUpdatedBy { get; set; }

        public int LastUpdatedByUserId { get; set; }

        [ForeignKey("CreatedByUserId")]
        public virtual User CreatedBy { get; set; }

        public int CreatedByUserId { get; set; }

        #endregion
    }

我已将此课程继承到CompanyStation:

public class CompanyStation : ServiceStation
    {
        #region '----- Member(s) -----'

        [InverseProperty("CompanyStation")]
        public virtual SapphirePosSystem SapphirePosSystem { get; set; }

        [ForeignKey("StoreManagerId")]
        public virtual User StoreManager { get; set; }

        public int StoreManagerId { get; set; }

        [ForeignKey("OfficeManagerId")]
        public virtual User OfficeManager { get; set; }

        public int OfficeManagerId { get; set; }

        #endregion
    }

当我这样做时,我不断收到StoreManager的外键循环错误错误。如果我删除该属性,那么我得到OfficeManager的错误。同样,如果我删除了我得到CreatedBy的错误,依此类推。所有外键都会抛出这种循环引用错误。我没有双向关系。不知道为什么Code First认为它是循环的。经过反复试验,我发现如果我把这段代码放在我的EntityConfiguration中,它就可以正常工作:

public class CompanyStationConfiguration : EntityTypeConfiguration<CompanyStation>
    {
        #region '----- Methods -----'

        public CompanyStationConfiguration()
            : base()
        {
            HasRequired(e => e.StoreManager).
                    WithMany().
                        HasForeignKey(e => e.StoreManagerId).
                            WillCascadeOnDelete(false);

            HasRequired(e => e.OfficeManager).
                   WithMany().
                       HasForeignKey(e => e.OfficeManagerId).
                           WillCascadeOnDelete(false);

            HasRequired(e => e.Company).
                   WithMany().
                       HasForeignKey(e => e.CompanyId).
                           WillCascadeOnDelete(false);

            HasRequired(e => e.LastUpdatedBy).
                WithMany().
                    HasForeignKey(e => e.LastUpdatedByUserId).
                        WillCascadeOnDelete(false);

            HasRequired(e => e.CreatedBy).
            WithMany().
                HasForeignKey(e => e.CreatedByUserId).
                    WillCascadeOnDelete(false);

            Map(e => { e.MapInheritedProperties(); e.ToTable("CompanyStations"); });
        }

任何人都可以告诉我为什么会发生这种情况并且我是否正确地解决了问题,或者它是否有点补丁工作?

提前致谢:)

0 个答案:

没有答案