2016-04-28 93 views
0

//這裏是讀取上傳文件的控制器。它在文件上傳到App_Data時成功工作,但是當上傳到MS SQL Server時,它會給出「無效對象dbo.Prescription 「當我向實體添加新記錄時,它給出DbUpdateException

using SastiDawaai.Models; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using System.IO; 
using System.Data.Entity.Infrastructure; 
using System.Data.Entity.Validation; 

namespace SastiDawaai.Controllers 
{ 
public class MedicineController : Controller 
{ 

    // GET: Medicine 
    public ActionResult Index() 
    { 
     MedicineContext medctx = null; 
     using(medctx=new MedicineContext()) 
     { 
     List<Medicine> medicinelist=medctx.Medicines.ToList(); 
     return View(medicinelist); 
     } 
    } 

    [HttpPost] 
    public ActionResult Index(HttpPostedFileBase file) 
    { 
     MedicineContext medctx = null; 
     Prescription pres = null; 
     if(file!=null && file.ContentLength>0) 
     { 
      ////upolading files to App_Server 
      var filename = Path.GetFileName(file.FileName); 
      var path = Path.Combine(Server.MapPath("~/App_Data"), filename); 
      file.SaveAs(path); 

      //uploading Files to database 
      var file_content=new BinaryReader(file.InputStream); 
      var content=file_content.ReadBytes(file.ContentLength); 

       using (medctx = new MedicineContext()) 
       { 
        pres = new Prescription 
        { 
         Prescription_Receipt = content, 
         File_Name = filename, 
         Submitted_Date = DateTime.Now, 


        }; 


        medctx.Prescriptions.Add(pres); 
        medctx.SaveChanges(); 

       } 



     } 
     return RedirectToAction("Index"); 
    } 






} 

}

//這裏是處方示範

using System; 
using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations; 
using System.ComponentModel.DataAnnotations.Schema; 
using System.Linq; 
using System.Web; 

namespace SastiDawaai.Models 
{ 

public class Prescription 
{ 
    [Key] 
    public int Prescription_Id { get; set; } 
    public byte[] Prescription_Receipt { get; set; } 
    public DateTime Submitted_Date { get; set; } 
    public string File_Name { get; set; } 
} 
} 

//這裏由具有2個DBSets所述的DbContext類」 Medicin e「和」處方「 //在獲取記錄和在Medicine實體中插入記錄時沒有問題,只有在添加記錄到添加到上下文的任何其他DBSet時纔會出現問題。

using System; 
using System.Collections.Generic; 
using System.Data.Entity; 
using System.Linq; 
using System.Web; 

namespace SastiDawaai.Models 
{ 
public class MedicineContext:DbContext 
{ 

    public virtual DbSet<Medicine> Medicines { get; set; } 
    public virtual DbSet<Prescription> Prescriptions { get; set; } 
} 
} 

回答

0

檢查您在數據庫表名

你的實體是處方藥和你的表名應該是處方,並檢查你的表模式,在你的實體是DBO讓你在你的數據庫表應該是相同的模式。

+0

表名是「處方」 –

+0

表名稱是「dbo.Prescription」在我的數據庫,我覺得是正確的型號名稱「處方」。 –

+0

因此將表格重命名爲處方或將模型中的表格屬性添加到。默認使用 EF使用複數名稱進行映射。 –

相關問題