对EntityFramework感到困惑

时间:2014-07-07 11:49:41

标签: c# asp.net entity-framework

我正在尝试使用jquery上传文件的示例。我创建了一个包含字段FileId,FileName,Filesize,FileExtention,filecontent的表,然后添加一个名为my model的实体数据模型,然后像在youtube视频中一样编写这段代码。但Visual Studio说

  

System.Data.Objects.ObjectQuery'不包含'添加'的定义您是否缺少装配参考

**dc.Uploaded.Add(new Uploaded**

但我添加了System.Data.Entity并添加了using ProjectsModel;

  {
        using (ProjectsEntities dc = new ProjectsEntities())
        {
            GridView1.DataSource = dc.Uploaded.ToList();
            GridView1.DataBind();
        }
    }


    protected void btnUploadAll_Click(object sender, EventArgs e)
    {
        HttpFileCollection filesColl = Request.Files;
        using (ProjectsEntities dc = new ProjectsEntities())
        {
            foreach (string uploader in filesColl)
            {
                HttpPostedFile file = filesColl[uploader];

                if (file.ContentLength > 0)
                {
                    BinaryReader br = new BinaryReader(file.InputStream);

                    byte[] buffer = br.ReadBytes(file.ContentLength);

                    dc.Uploaded.Add(new Uploaded
                    {
                        FileID = 0,
                        FileName = file.FileName,
                        ContentType = file.ContentType,
                        FileExtention = Path.GetExtension(file.FileName),
                        FileSize = file.ContentLength,
                        FileContent = buffer
                    });
                }
            }
            dc.SaveChanges();
        }
        PopulateUploadedFiles(); // for refresh grid data

1 个答案:

答案 0 :(得分:0)

Uploaded是实体类名,对吧?尝试:

dc.Uploadeds.Add

很明显,您不能在实体本身上使用Add,实体类不会定义Add方法,除非您明确地编写了其中一个。 OTOH实体集合通过继承具有Add方法。按照惯例,VS使用多个实体类生成集合。所以它应该是:

dc.Uploadeds.Add( ... )

现在清楚了吗?