无法将“DBContext.Models.Contact”类型的对象强制转换为“System.Data.Entity.Infrastructure.IObjectContextAdapter”类型

时间:2017-02-16 19:29:21

标签: c# asp.net-mvc-5 entity-framework-6 repository-pattern

我试图在Contact-Controller中实现“Repository-Pattern”和“Edit”方法,使用Contact-Repository中的“Attach Method”抛出错误。

import SwiftyJSON

class NewsTableViewController: UITableViewController {
    var ids             = [String]()
    var titles          = [String]()
    var descriptions    = [String]()
    var images          = [String]()
    var links           = [String]()
    var dates           = [String]()

    @IBOutlet var table_news: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        table_news.delegate = self
        getNews()
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false
        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return self.ids.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return 0
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:NewsTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "news_cell") as! NewsTableViewCell
        cell.lbl_date.text = self.dates[indexPath.row]
        return cell
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

    func getNews() {
        RestApiManager.sharedInstance.getNews { (json: JSON) in
            if let results = json.array {
                for entry in results {
                  self.ids.append(entry["id"].string!)
                  self.titles.append(entry["title"].string!)                      self.descriptions.append(entry["description"].string!)
                  self.links.append(entry["link"].string!)
                  self.dates.append(entry["date"].string!)
                }

                DispatchQueue.main.async{
                    //print(self.ids.count) it shows 16
                    self.table_news.reloadData()
                }
            }
        }
    }
}

在此问题出现之前,我在代码中遇到了另一个ObjectStateManger Extension not found错误:

Additional information: Unable to cast object of type 'Contacts.Models.Contact' to type 'System.Data.Entity.Infrastructure.IObjectContextAdapter'.

所以我不得不使用新的变量“manager”作为流量线程(ObjectStateManager no definition issue)上另一个堆栈的问题的解决方案 在Contact-Repository中附加方法

entities.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);

Contact Controller中使用ContactRespository编辑方法

public void Attach(Contact entity)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

           var manager = ((IObjectContextAdapter)entity).ObjectContext.ObjectStateManager;

            entities.Contacts.Attach(entity);

           manager.ChangeObjectState(entity, EntityState.Modified);

        }

1 个答案:

答案 0 :(得分:2)

在您引用的answer中,答案如下:

var manager = ((IObjectContextAdapter)db).ObjectContext.ObjectStateManager;
                                      ^^
                                      ||
                                   see this is db

这是有效的,因为该问题中的OP具有实现IObjectContextAdapter的类型。该问题的OP有这个:

SampleContext db = new SampleContext();

您正在尝试这样做:

var manager = ((IObjectContextAdapter)entity).ObjectContext.ObjectStateManager;

您的entity未实现该界面,因此您无法将其强制转换为IObjectContextAdapter,这正是错误消息告诉您的内容。