denmarkstan 0 Junior Poster in Training

I am new to vs2012.I am trying to run MVC3 tutorial to experience the working of vs2012. I have ran thesame tutorial on vs2010 successfully and inserted new record. Now I want to run thesame tutorial on vs2012. On both cases, i am using sqlserver management studio and entity framework(dotnet 4.0).I used SSMS2008 for VS2010 and SSMS2012 for VS2012. Program ran successfully on vs2012 but was unable to insert new record to database.Note i have googled this and tried
many suggestions all to no avail.. Here is the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LatestBlog.Models;
using System.Data.EntityModel;
using System.Text;

namespace LatestBlog.Controllers
{
    public class PostsController : Controller
    {
        private BlogEntities model = new BlogEntities();

        public ActionResult Index()
        {
            return View();
        }
        [ValidateInput(false)]
        public ActionResult Update(int? id, string title, string body, DateTime datetime, string tags)
        {
            if (!IsAdmin)
            {
                return RedirectToAction("Index");
            }
            Post post = GetPost(id);
            post.Title = title;
            post.Body = body;
            post.DateTime = datetime;
            post.Tags.Clear();
            tags = tags ?? string.Empty;
            string[] tagNames = tags.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string tagname in tagNames)
            {
                post.Tags.Add(GetTag(tagname));
            }
            if (!id.HasValue)
            {
                try
                {
                    //model.AddToPost(post);
                    model.Posts.Add(post);
                }
                catch (Exception exp)
                {
                    throw new Exception("ERROR: Unable to Add post to database - " + exp.Message.ToString(), exp);
                }                 

            }
            model.SaveChanges();
            return RedirectToAction("Details", new { id = post.ID });
        }
        public ActionResult Edit(int? id)
        {
            Post post = GetPost(id);
            StringBuilder tagList = new StringBuilder();//...........................
            foreach (Tag tag in post.Tags)
            {
                tagList.AppendFormat("{0}", tag.Name);
            }
            ViewBag.Tags = tagList.ToString();
            return View(post);
        }
        private Tag GetTag(string tagName)
        {
            return model.Tags.Where(x => x.Name == tagName).FirstOrDefault() ?? new Tag() { Name = tagName };
        }

        private Post GetPost(int? id)
        {
            return id.HasValue ? model.Posts.Where(x => x.ID == id).First() : new Post() { ID = -1 };
        }
        public bool IsAdmin
        {
            get
            {
                // To do, don't just return true
                return true; //Session["IsAdmin"] != null && (bool)Session["IsAdmin"]; 
            }
        }
    }
}



Connection Strings (I have tried):
 <add name="BlogEntities" connectionString="metadata=res://*/Models.Blog.csdl|res://*/Models.Blog.ssdl|res://*/Models.Blog.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=Blog;integrated security=True;MultipleActiveResultSets=True; " providerName="System.Data.EntityClient" />

    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-LatestBlog-20150104203236;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-LatestBlog-20150104203236.mdf" />

Dani AI

Generated

Common causes when an MVC app "runs" but no rows appear in the database are (a) the web app is connecting to a different database than the one you're inspecting, or (b) Entity Framework is treating the posted entity as an existing record instead of a new one (so no insert is issued). In VS2012 the default LocalDB / AttachDBFilename behavior and subtle model-binding of hidden ID fields are frequent culprits. — check both before changing model code.

Quick checks to run at runtime (put these just before SaveChanges so you see what the app is actually doing):

System.Diagnostics.Debug.WriteLine(model.Connection.ConnectionString);
System.Diagnostics.Debug.WriteLine(AppDomain.CurrentDomain.GetData("DataDirectory"));

If the connection string points to a LocalDB file or a different instance than the one you inspect in SSMS, that explains why you don't see inserts. Use SQL Profiler or the connection string output to confirm which physical database the app is writing to.

If the app truly connects to the right DB, check two EF issues: (1) the create/update decision in your action — a hidden ID on the create form will be posted back and can cause the code to skip adding the entity; remove the hidden ID for new-item views or explicitly treat non-positive IDs as "new"; (2) the EDMX mapping for the key should be store-generated (Identity) so EF knows the database will generate the key. Also wrap SaveChanges in a try/catch and log exceptions so errors aren't swallowed.

References: LocalDB behavior and AttachDBFilename issues can be reviewed at the Microsoft LocalDB docs (https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/sql-server-express-localdb?view=sql-server-ver16). For how EF tracks entity state and store-generated keys see the EF change-tracking guidance ().

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.