2010-01-11 34 views
0

我做了一個通用的保存功能的EF:EF 4.0問題將對象上下文

public void Save(T entity) 
    { 
     using (C context = new C()) 
     { 
      string entitySetName = context.FindEntitySetByEntity<T>(); 

      T entityInDDBB = GetEntityByKey(entity, entitySetName, context); 

      //if we didn't find the entity in database make an insert, if not an update. 
      if (entityInDDBB == null) 
      { 

       **context.AddObject(entitySetName, entity);** 
      } 
      else 
      { 
       context.ApplyCurrentValues(entitySetName, entity); 
      } 

      context.SaveChanges(); 
     } 
    } 

的問題是,如果我們通過派生類型ADDOBJECT(FE:老師),但映射預計人它會拋出一個錯誤。

我怎樣才能改變類型的對象(我想這是不可能的,而不需要創建一個新的),或者你知道任何其他方式使其工作?

問候。

+0

你得到的錯誤信息是什麼? – 2010-01-11 17:51:46

回答

2

那麼EF不允許您將一個CLR類視爲另一個CLR類。

即,您不能將教師視爲人。

鑑於此限制教師也必須是實體,否則這將始終失敗。

但是從您的描述來看,您聽起來好像沒有教師實體或教師映射信息?

不幸的是,沒有辦法解決這個問題。

亞歷

注:您的代碼應正常工作,如果你有一個老師實體和映射如果FindEntitySetByEntity<Teacher>()回報一樣FindEntitySetByEntity<Person>()