LINQ to SQL 不更新 MVC 2 应用程序中的数据库记录

发布于 2024-09-07 13:10:17 字数 3418 浏览 4 评论 0原文

我一直在尝试使用 MVC 2 制作这个唱片店项目。 创建记录有效,但更新记录无效。也不会抛出任何异常。

我在submitchanges()之前检查了getchangeset(),它显示全零。

感谢您的阅读和帮助:)

编辑视图:

<% using (Html.BeginForm("Edit", "Song")) { %>
    <fieldset>          
            <%: Html.HiddenFor(model => model.SongID) %>
            <%: Html.HiddenFor(model => model.DownloadCount) %>
            <%: Html.HiddenFor(model => model.Rating) %>
            <%: Html.HiddenFor(model => model.TagMapID) %>

        <div class="editor-label">
            <%= Html.LabelFor(model => model.AlbumID) %>
        </div>
        <div class="editor-field">
            <%= Html.DropDownListFor(model => model.AlbumID, DataHelper.getAlbumList(Model.AlbumID)) %>
            <%= Html.ValidationMessageFor(model => model.AlbumID) %>
        </div>

        <div class="editor-label">
            <%= Html.LabelFor(model => model.FullName) %>
        </div>
        <div class="editor-field">
            <%= Html.TextBoxFor(model => model.FullName)%>
            <%= Html.ValidationMessageFor(model => model.FullName) %>
and so on...

编辑功能

public ActionResult Edit(int id)
    {
        try
        {
            var model = songRepository.Song.Single(rec => rec.SongID == id);

            return View(model);
        }
        catch (Exception anyEx)
        {
            throw anyEx;
            //return View("Error")
        }
    }

编辑帖子功能

[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(Song model)
    {
        try
        {
            if (ModelState.IsValid)
            {
                songRepository.SaveSong(model);
                TempData["adminmsg"] = "Song saved";
                return RedirectToAction("List", "Song");
            }
            else
            {
                TempData["adminmsg"] = "Song not saved";
                return View("Edit", model);
            }
        }
        catch (Exception anyEx)
        {
            throw anyEx;
        }
    }

中 saveSong() 的样子,

public void SaveSong(Song song)
    {
        if (song.SongID == 0)
        {
            songTable.InsertOnSubmit(song);
        }
        else
        {
            songTable.Attach(song);
            songTable.Context.Refresh(RefreshMode.KeepChanges, song);
        }

        songTable.Context.SubmitChanges();
    }

这就是 SqlSongRepository [上下文事物]

这是上下文存储库

public class ContextRepository : IContextRepository
{
    private string connStr;

    public ContextRepository(string connectionString)
    {
        this.connStr = connectionString;
    }

    public DataContext MasterContext
    {
        get { return new DataContext(connectionString); }
    }

    public string connectionString
    {
        get { return connStr; }
    }
}

例如在歌曲控制器中

public SongController(IContextRepository contextRepository)
    {
        this.contextRepository = contextRepository;
        MasterContext = this.contextRepository.MasterContext;
        DataHelper.InitContext(contextRepository);

        songRepository = new SqlSongRepository(contextRepository.connectionString);
    }

那么 SongRepository 用作我之前发布过。

Using MVC 2 I have been trying to make this record store project.
Creating records work but updating them doesn't. No exceptions are thrown either.

I examined getchangeset() right before submitchanges() it shows all zeros.

Thanks for your reading and you help :)

The Edit view:

<% using (Html.BeginForm("Edit", "Song")) { %>
    <fieldset>          
            <%: Html.HiddenFor(model => model.SongID) %>
            <%: Html.HiddenFor(model => model.DownloadCount) %>
            <%: Html.HiddenFor(model => model.Rating) %>
            <%: Html.HiddenFor(model => model.TagMapID) %>

        <div class="editor-label">
            <%= Html.LabelFor(model => model.AlbumID) %>
        </div>
        <div class="editor-field">
            <%= Html.DropDownListFor(model => model.AlbumID, DataHelper.getAlbumList(Model.AlbumID)) %>
            <%= Html.ValidationMessageFor(model => model.AlbumID) %>
        </div>

        <div class="editor-label">
            <%= Html.LabelFor(model => model.FullName) %>
        </div>
        <div class="editor-field">
            <%= Html.TextBoxFor(model => model.FullName)%>
            <%= Html.ValidationMessageFor(model => model.FullName) %>
and so on...

Edit function

public ActionResult Edit(int id)
    {
        try
        {
            var model = songRepository.Song.Single(rec => rec.SongID == id);

            return View(model);
        }
        catch (Exception anyEx)
        {
            throw anyEx;
            //return View("Error")
        }
    }

Edit post function

[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(Song model)
    {
        try
        {
            if (ModelState.IsValid)
            {
                songRepository.SaveSong(model);
                TempData["adminmsg"] = "Song saved";
                return RedirectToAction("List", "Song");
            }
            else
            {
                TempData["adminmsg"] = "Song not saved";
                return View("Edit", model);
            }
        }
        catch (Exception anyEx)
        {
            throw anyEx;
        }
    }

This is what saveSong() looks like in SqlSongRepository

public void SaveSong(Song song)
    {
        if (song.SongID == 0)
        {
            songTable.InsertOnSubmit(song);
        }
        else
        {
            songTable.Attach(song);
            songTable.Context.Refresh(RefreshMode.KeepChanges, song);
        }

        songTable.Context.SubmitChanges();
    }

[Context things]

This is the context repository

public class ContextRepository : IContextRepository
{
    private string connStr;

    public ContextRepository(string connectionString)
    {
        this.connStr = connectionString;
    }

    public DataContext MasterContext
    {
        get { return new DataContext(connectionString); }
    }

    public string connectionString
    {
        get { return connStr; }
    }
}

In the song controller for example

public SongController(IContextRepository contextRepository)
    {
        this.contextRepository = contextRepository;
        MasterContext = this.contextRepository.MasterContext;
        DataHelper.InitContext(contextRepository);

        songRepository = new SqlSongRepository(contextRepository.connectionString);
    }

Then the songRepository is used as I posted before.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦醒时光 2024-09-14 13:10:17

为什么不尝试

public void SaveSong(Song song)
{
    if (song.SongID == 0)
    {
        context.songTable.InsertOnSubmit(song); //adds as song
    }
    else
    {
        var _song = (from s in context.songTable
                   where s.ID == song.id
                   select s).Single();
        _song = song; //updates existing song
    }

    context.songTable.SubmitChanges();
}

编辑:

这是我如何从我的存储库更新我的用户表的示例(抱歉它是在 VB 中)

Public Class UserRepository : Implements IUserRepository
    Private dc As MyDBDataContext
    Public Sub New()
        dc = New MyDBDataContext
    End Sub

   Public Sub AddUser(ByVal openid As OpenID) Implements IUserRepository.AddUser
        Dim user As New User
        user.MemberSince = DateTime.Now
        openid.User = user

        dc.OpenIDs.InsertOnSubmit(openid)
    End Sub

    Public Sub UpdateUser(ByVal user As User) Implements IUserRepository.UpdateUser
        Dim _user = (From u In dc.Users
            Where u.ID = user.ID
            Select u).Single

        With _user
            .About = user.About
            .BirthDate = user.BirthDate
            .Email = user.Email
            .isClosed = user.isClosed
            .isProfileComplete = user.isProfileComplete
            .RegionID = user.RegionID
            .Reputation = user.Reputation
            .UserName = user.UserName
            .WebSite = user.WebSite
        End With

    End Sub
End Class

然后在我的控制器中我决定是否要添加或更新。

why not try

public void SaveSong(Song song)
{
    if (song.SongID == 0)
    {
        context.songTable.InsertOnSubmit(song); //adds as song
    }
    else
    {
        var _song = (from s in context.songTable
                   where s.ID == song.id
                   select s).Single();
        _song = song; //updates existing song
    }

    context.songTable.SubmitChanges();
}

EDIT:

Here's an example of how I update my Users table from my Repository (sorry it's in VB)

Public Class UserRepository : Implements IUserRepository
    Private dc As MyDBDataContext
    Public Sub New()
        dc = New MyDBDataContext
    End Sub

   Public Sub AddUser(ByVal openid As OpenID) Implements IUserRepository.AddUser
        Dim user As New User
        user.MemberSince = DateTime.Now
        openid.User = user

        dc.OpenIDs.InsertOnSubmit(openid)
    End Sub

    Public Sub UpdateUser(ByVal user As User) Implements IUserRepository.UpdateUser
        Dim _user = (From u In dc.Users
            Where u.ID = user.ID
            Select u).Single

        With _user
            .About = user.About
            .BirthDate = user.BirthDate
            .Email = user.Email
            .isClosed = user.isClosed
            .isProfileComplete = user.isProfileComplete
            .RegionID = user.RegionID
            .Reputation = user.Reputation
            .UserName = user.UserName
            .WebSite = user.WebSite
        End With

    End Sub
End Class

Then in my controller I decide if I'm adding or updating.

烟花肆意 2024-09-14 13:10:17

嗯,解决了问题。更改

songTable.Context.Refresh(RefreshMode.KeepChanges, song);

songTable.Context.Refresh(RefreshMode.KeepCurrentValues, song);

成功。

我不知道为什么,如果有人能解释一下就太好了。

谢谢!

Well, solved the problem. Changing

songTable.Context.Refresh(RefreshMode.KeepChanges, song);

to

songTable.Context.Refresh(RefreshMode.KeepCurrentValues, song);

did the trick.

I don't know why, it would be great if someone could explain.

Thanks!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文