2015-01-20 5 views
0

Я пытаюсь выполнить обновление через EF 6 и иметь проблемы. Я относительно новичок в EF, поэтому, пожалуйста, простите меня, если вопрос немного тусклый. Я получаю следующее сообщение об ошибке При попытке обновить таблицу инструментов: Тип объекта HashSet`1 не является частью модели для текущего контекста.объект фреймворка обновления вложенные объекты

Я думаю, что это из-за вложенных объектов. Кто-нибудь знает, как их заполнять?

Заранее спасибо.

см. Код ниже моего обновления и модели.

 try 
     { 
      var i = (from x in _entities.Instrument 
           .Include("InstrumentAlias") 
           .Include("InstrumentMarketData") 
        where x.InstrumentKey == id 
        select x).First(); 

      _entities.Entry(i.InstrumentAlias).Property("InstrumentKey").IsModified = false; 
      _entities.Entry(i.InstrumentAlias).Property("InstrumentAliasKey").IsModified = false; 

      i.AccountGroupCode = src.AccountGroupCode; 
      i.AccountKey = src.AccountKey; 
      i.AccountType = src.AccountType; 
      i.BBGTicker = src.BBGTicker; 
      i.BoardLot = src.BoardLot; 
      i.BondPricingFactor = src.BondPricingFactor; 
      i.CashInstrument = src.CashInstrument; 
      i.ChinaShare = src.ChinaShare; 
      i.ContractSize = src.ContractSize; 
      i.CountryExposure = src.CountryExposure; 
      i.CountryIncorporation = src.CountryIncorporation; 
      i.CountryQuotation = src.CountryQuotation; 
      i.CouponFrequency = src.CouponFrequency; 
      i.CouponRate = src.CouponRate; 
      i.CUSIP = src.CUSIP; 
      i.ExpiryStyleKey = src.ExpiryStyleKey; 
      i.IndustryClass = src.IndustryClass; 
      i.InstrumentAlias = src.InstrumentAlias; 
      //i.InstrumentKey = src.InstrumentKey; 
      i.InstrumentLongName = src.InstrumentLongName; 
      i.InstrumentMarketData = src.InstrumentMarketData; 
      i.InstrumentName = src.InstrumentName; 
      i.InstrumentSectorCustomer = src.InstrumentSectorCustomer; 
      i.InstrumentTypeID = src.InstrumentTypeID; 
      i.ISIN = src.ISIN; 
      i.IssueDate = src.IssueDate; 
      i.LastUpdatedDateTime = src.LastUpdatedDateTime; 
      i.MaturityDate = src.MaturityDate; 
      i.OptionType = src.OptionType; 
      i.OTC = src.OTC; 
      i.PricingCurrency = src.PricingCurrency; 
      i.PrimaryExchange = src.PrimaryExchange; 
      i.ReportGroupCode = src.ReportGroupCode; 
      //i.SEDOL = src.SEDOL; 
      //i.Status = src.Status; 
      i.StrikePriceCurrency = src.StrikePriceCurrency; 
      i.UnderlyingInstrumentKey = src.UnderlyingInstrumentKey; 
      i.VotingRights = src.VotingRights; 



      i.InstrumentAlias.Select(x => x.ExternalInstrumentKey = src.InstrumentAlias.Select(y => y.ExternalInstrumentKey).First()); 
      i.InstrumentAlias.Select(x => x.SourceID = src.InstrumentAlias.Select(y => y.SourceID).First()); 




      this._entities.SaveChanges(); 
     } 


[Table("Instrument")] 
public partial class Instrument 
{ 
    public Instrument() 
    { 
     InstrumentAlias = new HashSet<InstrumentAlias>(); 
     InstrumentMarketData = new HashSet<InstrumentMarketData>(); 
     InstrumentSectorCustomer = new HashSet<InstrumentSectorCustomer>(); 
    } 

    [Key] 
    public int InstrumentKey { get; set; } 

    [StringLength(12)] 
    public string InstrumentTypeID { get; set; } 

    [Required] 
    [StringLength(40)] 
    public string InstrumentName { get; set; } 

    [Required] 
    [StringLength(85)] 
    public string InstrumentLongName { get; set; } 

    [StringLength(3)] 
    public string PricingCurrency { get; set; } 

    public decimal? CouponRate { get; set; } 

    [Column(TypeName = "date")] 
    public DateTime? MaturityDate { get; set; } 

    [StringLength(30)] 
    public string IndustryClass { get; set; } 

    [StringLength(16)] 
    public string SEDOL { get; set; } 

    [StringLength(16)] 
    public string ISIN { get; set; } 

    [StringLength(30)] 
    public string CUSIP { get; set; } 

    public int? CouponFrequency { get; set; } 

    public decimal? ContractSize { get; set; } 

    public decimal? BoardLot { get; set; } 

    [StringLength(10)] 
    public string PrimaryExchange { get; set; } 

    [Column(TypeName = "date")] 
    public DateTime? IssueDate { get; set; } 

    public decimal? BondPricingFactor { get; set; } 

    [Required] 
    [StringLength(1)] 
    public string Status { get; set; } 

    [StringLength(2)] 
    public string CountryExposure { get; set; } 

    [StringLength(2)] 
    public string CountryQuotation { get; set; } 

    [StringLength(2)] 
    public string CountryIncorporation { get; set; } 

    public int? ReportGroupCode { get; set; } 

    [StringLength(3)] 
    public string StrikePriceCurrency { get; set; } 

    public int? ExpiryStyleKey { get; set; } 

    [StringLength(4)] 
    public string OptionType { get; set; } 

    [StringLength(1)] 
    public string AccountType { get; set; } 

    [StringLength(3)] 
    public string AccountGroupCode { get; set; } 

    public int? UnderlyingInstrumentKey { get; set; } 

    public DateTime LastUpdatedDateTime { get; set; } 

    public int? AccountKey { get; set; } 

    public bool? CashInstrument { get; set; } 

    public bool? OTC { get; set; } 

    public decimal? VotingRights { get; set; } 

    [StringLength(1)] 
    public string ChinaShare { get; set; } 

    [StringLength(30)] 
    public string BBGTicker { get; set; } 

    public virtual ICollection<InstrumentAlias> InstrumentAlias { get; set; } 

    public virtual ICollection<InstrumentMarketData> InstrumentMarketData { get; set; } 

    public virtual ICollection<InstrumentSectorCustomer> InstrumentSectorCustomer { get; set; } 
} 
+0

Несомненно, ваш фрагмент не должен быть Великой стеной кода, чтобы воспроизвести проблему. Можете ли вы уложить это на что-то большее, чем размер укуса, который все еще показывает проблему? –

ответ

1

Если вы хотите использовать lambda version из Property вы бы сразу увидеть что-то не так. Это будет выглядеть как

_entities.Entry(i.InstrumentAlias) 
    .Property(x => x.InstrumentKey) 
    .IsModified = false; 

Приглядевшись, вы заметите, что IntelliSense не показывает x.InstrumentKey. Почему нет? Потому что не InstrumentAlias, а ICollection<InstrumentAlias>. Код даже не компилируется.

Проблема заключается в том, что Entry должен вернуть объект DbEntityEntry, объект, содержащий информацию о модели EF об одном экземпляре класса сущности. Класс сущности - это класс, который является частью модели для текущего контекста.

Так что это исключение, является (ICollection реализован как) HashSet и HashSet не является частью модели.

Так что вы пытаетесь достичь там, он должен начать с

_entities.Entry(i) 

Или, если вы хотите, чтобы отметить все InstrumentKey в InstrumentAlias коллекции, как изменяется, вы должны перебрать эту коллекцию:

foreach(var ialias in i.InstrumentAlias) 
{ 
    _entities.Entry(ialias).Property(x => x.InstrumentKey).Modified = true; 
} 

Замечание: когда-либо слышали о AutoMapper?

Смежные вопросы