尝试使用EF更新实体并使用WCF发送它 - 属性导致更新方案中出现异常

时间:2016-02-24 15:48:23

标签: c# wcf entity-framework-5

我尝试使用WCF发送对象。使用EF从数据库中检索对象。

这是我得到的例外:

enter image description here

这仅在更新方案中发生。插入效果很好。
跟踪错误,我发现问题出在我最近添加的一个集合(称为Travelers)。

当我在WCF发送更新的实体之前,在更新之后尝试在运行时观察其值时会发生什么:

enter image description here

这是违法的班级'属性声明(我尝试取消注释DataMember属性,但它没有工作):

[DataContract]
public class Travel : InsuredObject, ISaleEntity, ICloneable
{    
    //[DataMember]
    public virtual ICollection<Traveler> Travelers { get; set; } 
    ...  

我已经读过this.Configuration.ProxyCreationEnabled = false;和/或this.Configuration.LazyLoadingEnabled = false;可能会修复它,但我无法改变这些因为我以外的原因,即使我尝试使用它们 - 我还有一些例外......

附加代码:
更新方法:

public virtual TEntity CreateAndUpdate(int saleId, TEntity entity) {
    var context = ((IObjectContextAdapter)this.Context).ObjectContext;

    var objBaseSet = context.CreateObjectSet<TBase>();

    var entityBaseKey = context.CreateEntityKey(objBaseSet.EntitySet.Name, entity);
    Object foundBaseEntity;
    var baseExists = context.TryGetObjectByKey(entityBaseKey, out foundBaseEntity);

    entity.Id = saleId;

    if (!baseExists) {
        this.GetDbSet<TEntity>().Add(entity); 
    }

    this.objectContext.SaveChanges();

    return entity;
}  

在更新之前检索包含对象:

public virtual IQueryable<TEntity> GetAll(Expression<Func<TEntity, bool>> where, bool brutalRefresh = false) {

    IQueryable<TEntity> retObj = this.GetDbSet<TEntity>();
    if (where != null) {
        retObj = retObj.Where(where);
    }

    if (brutalRefresh) {
        var context = ((IObjectContextAdapter)this.Context).ObjectContext;
        context.Refresh(RefreshMode.StoreWins, retObj);
    }

    return retObj;
}

...所有代码都是与其他项目共同的代码,它发送和接收与我相同的实体,它只是我添加的Travel实体,这会导致我出现问题,所以我正在寻找的解决方案应该包括公共代码中的0个更改。

Traveler上课(完全):

 [DataContract]
    public class Traveler : ISaleEntity, ICloneable
    {
        [DataMember]
        public int Id { get; set; }

        [DataMember]
        public string FirstName { get; set; }

        [DataMember]
        public string LastName { get; set; }

        [DataMember]
        public string IDNumber { get; set; }

        [DataMember]
        public DateTime? BirthDate { get; set; }

        [DataMember]
        public virtual ICollection<SelectedCoverage> SelectedCoverages { get; set; }

        [NotMapped]
        public List<MedicalQuestionnaireAnswer> MedicalQuestionnaireAnswers
        {
            get
            {
                if (string.IsNullOrWhiteSpace(DBMedicalQuestionnaireAnswers))
                    return new List<MedicalQuestionnaireAnswer>();

                return DBMedicalQuestionnaireAnswers.Split(',')
                    .Select(c => (MedicalQuestionnaireAnswer)int.Parse(c)).ToList();
            }
            set { DBMedicalQuestionnaireAnswers = string.Join(",", value.Select(m => (int)m)); }
        }

        [NotMapped]
        public Genders Gender
        {
            get { return (Genders)DBGender; }
            set { DBGender = (int)value; }
        }

        /// <summary>
        /// NOTE! Do not use this property directly! use MedicalQuestionnaireAnswers instead
        /// </summary>
        [DataMember]
        public string DBMedicalQuestionnaireAnswers { get; set; }

        /// <summary>
        /// NOTE! Do not use this property directly! use Gender instead
        /// </summary>
        [DataMember]
        public int DBGender { get; set; }

        public object Clone()
        {
            Traveler traveler = new Traveler();
            traveler.FirstName = this.FirstName;
            traveler.LastName = this.LastName;
            traveler.IDNumber = this.IDNumber;
            traveler.BirthDate = this.BirthDate;
            traveler.DBMedicalQuestionnaireAnswers = this.DBMedicalQuestionnaireAnswers;
            traveler.Gender = this.Gender;
            if (this.SelectedCoverages != null)
            {
                traveler.SelectedCoverages = this.SelectedCoverages.Select(sc => (SelectedCoverage)sc.Clone()).ToList();
            }

            return traveler;
        }
    }

    public static class TravelerExtension
    {

        /// <summary>
        /// copy all the property except from the id and src defualt values
        /// </summary>
        /// <param name="dbTraveler"></param>
        /// <param name="src"></param>
        public static void CopyTravelerProperties(this Traveler target, Traveler src)
        {
            target.FirstName = src.FirstName;
            target.LastName = src.LastName;
            target.IDNumber = src.IDNumber;
            target.BirthDate = src.BirthDate;
            target.DBMedicalQuestionnaireAnswers = src.DBMedicalQuestionnaireAnswers;
            target.DBGender = src.DBGender;
            target.SelectedCoverages.CopySelectedCoveragesProperties(src.SelectedCoverages);
        }
    }

    public static class TravelersExtension
    {

        /// <summary>
        /// copy all the property except from the id and src defualt values
        /// </summary>
        /// <param name="dbTravelers"></param>
        /// <param name="src"></param>
        public static void CopyTravelersProperties(this ICollection<Traveler> target, ICollection<Traveler> src)
        {

            List<int> allTravelersIdsSrc = src.Select(t => t.Id).ToList();

            // remove ids exist target and not in src 
            target.ToList().RemoveAll(t => allTravelersIdsSrc.Contains(t.Id));


            target = target ?? new List<Traveler>();
            foreach (Traveler srcTraveler in src)
            {
                var targetTraveler = target.FirstOrDefault(targetTrv => srcTraveler.Id != 0 && targetTrv.Id == srcTraveler.Id);
                // if not exist traveler with target traveler id in db
                if (targetTraveler == null)
                {
                    // add srcTraveler to target
                    target.Add(srcTraveler);
                }
                else
                {
                    targetTraveler.CopyTravelerProperties(srcTraveler);
                }

            }
        }
    }

更多信息:
如果在尝试获取即时窗口中的值之前调用ToList(),则不会发生直接窗口异常。问题本身仍然存在。

尝试评论[DataMember]属性:

public virtual ICollection<SelectedCoverage> SelectedCoverages { get; set; }
Traveler课程中的

没有影响。

例外:

enter image description here

更多信息2:

只有一个实体导致异常:

public class Quote : ISaleEntity, ICloneable {      
    ...
        [DataMember]
        public virtual Travel Travel { get; set; } 
    ...   

当我将上述[DataMember]更改为[IgnoreDataMember]时 - 没有例外。

我将此类的所有属性设置为[IgnoreDataMember]

[DataContract]
    public class Travel : InsuredObject, ISaleEntity, ICloneable
    {
         [IgnoreDataMember]
        //[DataMember]
        public bool? IsFromIsrael { get; set; }

        [IgnoreDataMember]
        //[DataMember]
        public virtual ICollection<Traveler> Travelers { get; set; }

        [IgnoreDataMember]
        public virtual Quote Quote { get; set; }

          [IgnoreDataMember]
        //[DataMember]
        [NotMapped]
        public List<int> DestinationsCodes
        {
            get
            {
                if (string.IsNullOrWhiteSpace(DBDestinationsCodes))
                    return new List<int>();

                return DBDestinationsCodes.Split(',').Select(c => int.Parse(c)).ToList();
            }

            set { DBDestinationsCodes = string.Join(",", value); }
        }

        /// <summary>
        /// NOTE! Do not use this property directly! use DestinationsCodes instead
        /// </summary>
             [IgnoreDataMember]
        //[DataMember]
        public string DBDestinationsCodes { get; set; }
        ...  

但异常仍然存在。可能是因为这个类继承自以下类:

[DataContract]
    [KnownType(typeof(Vehicle))]
    [KnownType(typeof(Apartment))]
    [KnownType(typeof(Travel))]
    public class InsuredObject : ISaleEntity, ICloneable {
        [Key]
        [DataMember]
        public int Id { get; set; }

        [DataMember]
        public int? OwnerTypeId { get; set; }


        //navigation property

        [DataMember]
        public bool? HasShiabud { get; set; }

        [DataMember]
        [IgnoreDataMember]
        public virtual Shiabud Shiabud { get; set; }

        //[NotMapped]
        //public virtual Proposal Proposal { get; set; }

        //[DataMember]
        [IgnoreDataMember]
        public virtual ICollection<Coverage> Coverages { get; set; }  
        ...

那么如何通过WCF发送此实体?

2 个答案:

答案 0 :(得分:1)

通过使您的属性成为虚拟,您正在做的是延迟加载。

您可以改为将属性设置为ICollection,而是进行急切加载。

答案 1 :(得分:0)

您可以与执行数据库更新的EF上下文共享代码的一部分吗?

从错误消息中我收集到的不是WCF正在玩技巧。相反,看起来EF ObjectContent已经在您应用更改时被处置(SaveChanges()方法)。如果你在WCF方法调用之间保持活动,例如,将它作为后端的静态变量并将其放在using子句中。

这应该可以将延迟加载应用于EF 6及更高版本的数据库上下文,尽管它对旧版本的工作方式类似。 (我实现了一个继承的类来帮助处理配置。这可能不是必需的)

public class DomainDbContext : DbContext
{
    Configuration.LazyLoadingEnabled = false;
}