Mappan
Mappan

Reputation: 2617

Cannot convert from table to class

I am making an MVC 3 Article app and connecting it to a SQL database with LINQ. I'm trying to create a new article with LINQ code and I keep ending up with these errors:

ArticleRepository.cs(41,13,41,47): error CS1502: The best overloaded method match for 'System.Data.Linq.Table.InsertOnSubmit(NyjiGrunnur.ArticleTable)' has some invalid arguments

ArticleRepository.cs(41,45,41,46): error CS1503: Argument 1: cannot convert from 'NyjiGrunnur.Models.Article' to 'NyjiGrunnur.ArticleTable'

Add article function:

public void AddArticle(Article s)
    {
        ArticleLINQDataContext db = new ArticleLINQDataContext();
        //Article a = new Article { Id = s.Id, Content = s.Content, Name = s.Name, Subject =        s.Subject, Created = (DateTime)s.Created };
    Line 41:    db.ArticleTables.InsertOnSubmit(s);
        db.SubmitChanges();
    }

I have Articles.cs model:

namespace NyjiGrunnur.Models
{
    public class Article
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Content { get; set; }
        public string Subject { get; set; }
        public DateTime Created { get; set; }
    }
}

I have LINQ to SQL classes that I'm working with. I also have a Edit function that works and is like this:

public void UpdateArticle(Article s)
    {
      ArticleLINQDataContext db = new ArticleLINQDataContext();

      var a = (from article in db.ArticleTables
                   where article.Id == s.Id
                   select article).SingleOrDefault();
      a.Name = s.Name;
      a.Subject = s.Subject;
      a.Content = s.Content;
      a.Created = s.Created;
      a.Id = s.Id;
      db.SubmitChanges();

    }

HomeController should also be working fine.

Upvotes: 1

Views: 1368

Answers (2)

D Stanley
D Stanley

Reputation: 152634

Looks like you were on track with AddArticle but commented out the mapping:

public void AddArticle(Article s)
{
    ArticleLINQDataContext db = new ArticleLINQDataContext();
    ArticleTable a = 
        new ArticleTable { 
                             Id = s.Id, // *see question below code sample
                             Content = s.Content, 
                             Name = s.Name, 
                             Subject = s.Subject, 
                             Created = (DateTime)s.Created 
                         };
    db.ArticleTables.InsertOnSubmit(a);   // <-- note it's "a" instead of "s"
    db.SubmitChanges();
}

*Is Id auto-generated? If so you shouldn't be setting it when you insert it.

Upvotes: 1

SLaks
SLaks

Reputation: 888205

As the error is trying to tell you, your LINQ to SQL classes use the ArticleTable class, which is not the same as the Article class.

You need to create an ArticleTable (data model) instance from the Article (view model) so that you can put it in the database.

Upvotes: 4

Related Questions