2013-04-02 42 views
0

我正在使用MVC C#和實體框架工作。如何將部分視圖數據分配給c#MVC中的模型?

因此,在我的部分觀點,我想改變數據。

這是我的控制器

public ActionResult BusinessDetails(){    
    int bsId = bskey ?? default(int); 
    var BusinessQuery = GetBusinessById(bsId);  
    var PeopleQuery = BusinessQuery.t_PEOPLE 
         .Where(p => p.PP_IS_CONTACT == true).AsEnumerable(); 

    var peopleCollection = new EntityCollection<t_PEOPLE>(); 

    foreach (var m in PeopleQuery) 
    { 
     //This is problem.----------- 
     peopleCollection.Add(m); 
    } //-------------- 

    BusinessQuery.t_PEOPLE = peopleCollection;  
    return PartialView("_EditBusiness", BusinessQuery); 
    }      

    return RedirectToAction("Index");    
} 


public t_BUSINESS GetBusinessById(int id){ 
    if (id == 0) 
     return null; 

    var query = from b in db.t_BUSINESS 
       where b.BS_KEY == id 
       select b; 
    var Business = query.FirstOrDefault(); 
    return Business; 
} 

那麼,如何分配PeopleQueryBusinessQuery.t_PEOPLE

療法是錯誤,並說

The object could not be added to the EntityCollection or EntityReference. An object that is attached to an ObjectContext cannot be added to an EntityCollection or EntityReference that is not associated with a source object 

回答

1

試試這個

var PeopleQuery = BusinessQuery.t_PEOPLE.Where(p => p.PP_IS_CONTACT == true).ToList(); 
2

你可以直接查詢您正在尋找的記錄:

public ActionResult BusinessDetails() 
{    
    int bsId = bskey ?? default(int); 
    var business = GetContactBusinessById(bsId);  
    return PartialView("_EditBusiness", business); 
} 

public t_BUSINESS GetContactBusinessById(int id) 
{ 
    if (id == 0) 
    { 
     return null; 
    } 

    var query = 
     from b in db.t_BUSINESS 
     from p in b.t_PEOPLE 
     where b.BS_KEY == id && p.PP_IS_CONTACT 
     select b; 

    return query.FirstOrDefault(); 
} 
相關問題