两个表数据CRUD操作在一个代码中第一个实体框架

时间:2016-08-14 10:29:32

标签: entity-framework asp.net-mvc-4 code-first

我在城市和州有两张桌子。 我想在一个列表中显示状态表中的城市数据+ st_name。

我使用下面的模型在一个列表中显示两个表数据但是。 当我尝试在城市细节中执行删除操作时,它给出了如何解决此问题的错误。??

城市模型: -

 namespace ms2app.Models.Entity
 {
   public partial class CITY_MASTER
   {
      public int CT_ID { get; set; }

    [Required(ErrorMessage = "Please enter City Code.")]
    [StringLength(3, ErrorMessage = "City Code should not be more than {1} characters.")]
    public string CT_CODE { get; set; }

    [Required(ErrorMessage = "Please enter City Name.")]
    [StringLength(100, ErrorMessage = "City Name should not be more than {1} characters.")]
    public string CT_NAME { get; set; }

    [Required(ErrorMessage = "Please enter STD Code.")]
    [StringLength(50, ErrorMessage = "STD Code should not be more than {1} characters.")]
    public string CT_STD_CODE { get; set; }
    public Nullable<int> CT_ST_ID { get; set; }
    public System.DateTime LAST_UPDATE_DATE { get; set; }
    public bool IS_DEACTIVE { get; set; }

    [Required(ErrorMessage = "Please select state.")]
    public string ST_NAME { get; set; }


}

}

我的控制器删除方法: -

public ActionResult Delete(int id)
    {
        try
        {

            CITY_MASTER cityMaster = db.CITY_MASTER.Find(id);
            cityMaster.IS_DEACTIVE = false;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        catch (Exception ex)
        {
            throw ex;
        }

    }

Example

1 个答案:

答案 0 :(得分:0)

您的逻辑没有实际的删除操作。

试试这个......

public ActionResult Delete(int id)
    {
        try
        {

            CITY_MASTER cityMaster = db.CITY_MASTER.Find(id);
            cityMaster.IS_DEACTIVE = false;
            db.Entry(cityMaster).State = System.Data.Entity.EntityState.Deleted; 
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        catch (Exception ex)
        {
            throw ex;
        }

    }