mardi 10 mai 2016

An entity object cannot be referenced by multiple instances of IEntityChangeTracker"

this is my Class to cash the currently logged user when i am getting this error but i can figure it out while searching the error i am not getting any idea.my model class have the property public virtual User User{get;set;}

public static class Auth
{
    private const string UserKey = "BlogwithEf.Auth.UserKey";
    public static User User {
        get
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
                return null;
            var user = HttpContext.Current.Items[UserKey] as User;
            if (user == null)
            {
                var db= new Database();
                user = db.Users.FirstOrDefault(u => u.Username == HttpContext.Current.User.Identity.Name);
                if (user == null)
                    return null;
                HttpContext.Current.Items[UserKey] = user;
            }
            return user;

        }
    }
}

this is my controller code

[HttpPost,ValidateAntiForgeryToken]
    public ActionResult New(PostsNew form)
    {
        if (!ModelState.IsValid)
            return View(form);

        var post = new Post
        {
            User = Auth.User,
CreatedAt=DateTime.UtcNow,
Title = form.Title,
Slug = form.Slug,
Content = form.Content
        };

        //Error is here

        Database.Posts.Add(post);

        Database.SaveChanges();

        return RedirectToAction("Index");

    }

Aucun commentaire:

Enregistrer un commentaire