Tomek Krupa Tomek Krupa - 4 months ago 27
C# Question

Entity Framework Code First, MVC, SqlException

I have a problem with code-first approach

My model:

public class Articles
{
[Key]
public int ArticleID { get; set; }

[Required(ErrorMessage ="Wymagane podanie tytułu!")]
public string Title { get; set; }
[Required(ErrorMessage = "Wymagane podanie krótkiego opisu!")]
public string ShortDesc { get; set; }
[Required(ErrorMessage = "Wymagane podanie treści!")]
public string Content { get; set; }
public string Author { get; set; }
public string Tags { get; set; }
}


My connection strings in
web.config
:

<connectionStrings>
<add name="ArticlesSConnectionString"
connectionString="Data Source=(LocalDb)\v11.0; Initial Catalog=BazaA;Integrated Security=SSPI"
providerName="System.Data.SqlClient" />
</connectionStrings>


Context:

public class ArticlesContext : DbContext
{
public ArticlesContext() : base("ArticlesConnectionString") { }
public DbSet<Articles> ArticlesS { get; set; }
}


Controller:

public class AdminController : Controller
{
// GET: Admin
public ActionResult Index()
{
return View();
}

[HttpPost]
public ActionResult addArticle(Articles article)
{
if (!ModelState.IsValid) { return View("Index", article); }
else
{
ArticlesContext db = new ArticlesContext();

db.ArticlesS.Add(article);
db.SaveChanges();

return View("Index");
}
}
}


Error:


An exception of type 'System.Data.SqlClient.SqlException' occurred in
EntityFramework.dll but was not handled in user code


on line:

db.ArticlesS.Add(article);


I have no idea what is wrong...

Answer

Got to services and start SQL Server or your Conn string is not good I think that you must have Context class name inside Connection string,

<connectionStrings>
<add name="ArticlesContext" 
     connectionString="Data Source=(LocalDb)\v11.0;AttachDbFileName=|DataDirectory|\BazaA.mdf; Initial Catalog=BazaA;Integrated Security=SSPI" 
     providerName="System.Data.SqlClient" />