Daniel Andrei Popescu Ответов: 0

Не существует сопоставления типа объекта wpfattendanceapp.model.availablecourses с известным собственным типом управляемого поставщика


Привет,

У меня есть проблема, когда я хочу сохранить данные, так как я получаю эту ошибку:
No mapping exists from object type WPFAttendanceApp.Model.AvailableCourses to a known managed provider native type
Теперь я проверил связь моих таблиц,привязку,а также запросы, но все, кажется, в порядке.Это мои столы:
CREATE TABLE [dbo].[AttendanceList] (
    [sNr]           INT            NOT NULL,
    [SN]            CHAR (10)      NOT NULL,
    [fName]         NVARCHAR (MAX) NOT NULL,
    [lName]         NVARCHAR (MAX) NOT NULL,
    [dateArrival]   ROWVERSION     NOT NULL,
    [dateDeparture] DATETIME       NOT NULL,
    [hoursSpent]    INT            NOT NULL,
    PRIMARY KEY CLUSTERED ([sNr] ASC),
    CONSTRAINT [FK_AttendanceList_ToTable] FOREIGN KEY ([SN]) REFERENCES [dbo].[RegisterStudent] ([SN])
);

CREATE TABLE [dbo].[AvailableCourses] (
    [CourseID]   INT           NOT NULL,
    [ClassID]    INT           NULL,
    [courseName] NVARCHAR (50) NOT NULL,
    [education]  NVARCHAR (50) NOT NULL,
    PRIMARY KEY CLUSTERED ([CourseID] ASC)
);

CREATE TABLE [dbo].[RegisterStudent] (
    [SN]       CHAR (10)      NOT NULL,
    [sNr]      INT            NOT NULL,
    [fName]    NVARCHAR (MAX) NOT NULL,
    [lName]    NVARCHAR (MAX) NOT NULL,
    [semester] INT            NULL,
    PRIMARY KEY CLUSTERED ([SN] ASC)
);

CREATE TABLE [dbo].[RegisterTeacher] (
    [SNTeacher]  CHAR (10)      NOT NULL,
    [UserName]   NVARCHAR (MAX) NOT NULL,
    [pwd]        CHAR (10)      NOT NULL,
    [fullName]   NVARCHAR (MAX) NOT NULL,
    [CourseName] NVARCHAR (50)  NOT NULL,
    [pwd2]       CHAR (30)      NOT NULL,
    PRIMARY KEY CLUSTERED ([SNTeacher] ASC)
);

CREATE TABLE [dbo].[ReportAttendance] (
    [SNTeacher]  CHAR (10)      NOT NULL,
    [sNr]        INT            NOT NULL,
    [Name]       NVARCHAR (MAX) NULL,
    [hoursSpent] INT            NULL,
    [CourseID]   INT            NULL,
    PRIMARY KEY CLUSTERED ([sNr] ASC),
    CONSTRAINT [FK_ReportAttendance_ToTable] FOREIGN KEY ([SNTeacher]) REFERENCES [dbo].[RegisterTeacher] ([SNTeacher]),
    CONSTRAINT [FK_ReportAttendance_ToTable_1] FOREIGN KEY ([CourseID]) REFERENCES [dbo].[AvailableCourses] ([CourseID])
);

CREATE TABLE [dbo].[TeacherCourses] (
    [CourseID]  INT       NULL,
    [PKey]      INT       IDENTITY (1, 1) NOT NULL,
    [SNTeacher] CHAR (10) NOT NULL,
    PRIMARY KEY CLUSTERED ([PKey] ASC),
    CONSTRAINT [FK_TeacherCourses_ToTable_1] FOREIGN KEY ([SNTeacher]) REFERENCES [dbo].[RegisterTeacher] ([SNTeacher]),
    CONSTRAINT [FK_TeacherCourses_ToTable] FOREIGN KEY ([CourseID]) REFERENCES [dbo].[AvailableCourses] ([CourseID])
);

Теперь ошибка говорит о том,что у меня есть проблема в моем классе AvailableCours из моей модели, но там, похоже, тоже все в порядке:
public partial class AvailableCours:INotifyPropertyChanged
  {
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
      public AvailableCours()
      {
          this.ReportAttendances = new ObservableCollection<ReportAttendance>();
          this.TeacherCourses = new ObservableCollection<TeacherCours>();
      }
      private bool isChecked;
      public bool IsChecked
      {
          get { return isChecked; }
          set
          {
              if(isChecked!=value)
              {
                  isChecked = value;
                  NotifyOnPropertyChange("IsChecked");
              }
          }
      }
      protected void NotifyOnPropertyChange(String propertyName)
      {
          if (PropertyChanged != null)
          {
              PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
          }
      }
      public int CourseID { get; set; }
      public Nullable<int> ClassID { get; set; }
      public string courseName { get; set; }
      public string education { get; set; }

      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
      public virtual ObservableCollection<ReportAttendance> ReportAttendances { get; set; }
      [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
      public virtual ObservableCollection<TeacherCours> TeacherCourses { get; set; }

      public event PropertyChangedEventHandler PropertyChanged;
  }

И,наконец, функция, которую я использую для сохранения данных:
public void SaveTeacher(object param)
      {
          string connectionString = null;

          connectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\user0909\\Documents\\AttendanceListStudents.mdf;Integrated Security=True;Connect Timeout=30";
          try
          {
              using (SqlConnection con = new SqlConnection(connectionString))
              {
                  con.Open();
                  string sql = "Insert into RegisterTeacher(SNTeacher,UserName,pwd,fullName,education)values(@SNTeacher,@UserName,@pwd,@fullName,@education)";
              using (SqlCommand com = new SqlCommand(sql,con ))
                      {
                          com.Parameters.AddWithValue("@SNTeacher", SqlDbType.Int).Value = SNTeacher;
                          com.Parameters.AddWithValue("@UserName", SqlDbType.NVarChar).Value = UserName;
                          com.Parameters.AddWithValue("@pwd", SqlDbType.NVarChar).Value = pwd;
                          com.Parameters.AddWithValue("@fullName", SqlDbType.NVarChar).Value = fullName;
                          com.Parameters.AddWithValue("@education", SqlDbType.NVarChar).Value = education;
                          com.ExecuteNonQuery();//this is for storing data into table RegisterTeacher
                      }

                  using (SqlCommand cmd = new SqlCommand("", con))
                  {
                      var query = new System.Text.StringBuilder();
                      query.Append("INSERT INTO TeacherCourses (CourseID, SNTeacher) SELECT @CourseID, @SNTeacher FROM AvailableCourses WHERE courseName IN (");
                      bool started = false;
                      foreach (var item in Courses)
                      {
                          if (item.IsChecked)
                          {
                              string name = "@courseName" + cmd.Parameters.Count;
                              cmd.Parameters.AddWithValue(name, item.courseName);

                              if (started) query.Append(',');
                              query.Append(name);
                              started = true;
                          }
                      }

                      if (started)
                      {
                          query.Append(')');
                          cmd.CommandText = query.ToString();
                          cmd.Parameters.AddWithValue("@SNTeacher", SNTeacher);
                          cmd.ExecuteNonQuery();//this is for storing data in TeacherCourses table
                      }




                  }
              }
          }

          catch (Exception e)
          {
              MessageBox.Show(e.Message);
          }
          finally
          {
              MessageBox.Show("Registration successful!");

          }
      }


Что я уже пробовал:

Я пытался переделать базу данных, но это было напрасно.В чем может быть проблема?Может кто-нибудь дать мне совет?Заранее благодарю вас!

0 Ответов