ASP.NET MVC3 + Entity Framework实现数据按需更新

1.Entity Framework支持数据按需更新吗?

ASP.NET MVC3 + Entity Framework要实现数据按需更新,前提条件是Entity Framework要支持数据按需更新。我们先做个测试验证下,下边是一个实体类:
public class Pet
{
    public Pet()
    {
        this.Id = 0;            
        this.PersonId = 0;
        this.Name = "";
    }

    public int Id { get; set; }
    public Nullable<int> PersonId { get; set; }
    public string Name { get; set; }
}

Entity Framework更新数据:
testContext db = new testContext();
Pet pet = db.Pets.FirstOrDefault();
pet.Name = "newname1";
db.SaveChanges();

SQL Server Profiler跟踪结果:
引用内容 引用内容
exec sp_executesql N'update [dbo].[Pet]
set [Name] = @0
where ([Id] = @1)
',N'@0 nvarchar(20),@1 int',@0=N'newname1',@1=1

可见,Entity Framework支持数据按需更新。

2.ASP.NET MVC3 + Entity Framework还是按需更新吗?

View(注意没有PersonId):
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Pet</legend>

        @Html.HiddenFor(model => model.Id)

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

Controller:
[HttpPost]
public ActionResult Edit(Pet pet)
{
    if (ModelState.IsValid)
    {
        db.Entry(pet).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(pet);
}

SQL Server Profiler跟踪结果:
引用内容 引用内容
exec sp_executesql N'update [dbo].[Pet]
set [PersonId] = @0, [Name] = @1
where ([Id] = @2)
',N'@0 int,@1 nvarchar(20),@2 int',@0=0,@1=N'newname2',@2=1

很明显,PersonId使用了默认值进行更新,下边我们对Controller代码稍做修改:

[HttpPost]
public ActionResult Edit(Pet pet)
{
    if (ModelState.IsValid)
    {
        //var entry = db.Entry(pet);[1]
        var entry = db.Entry(db.Pets.Attach(pet));
        entry.Property("Name").IsModified = true;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(pet);
}

SQL Server Profiler跟踪结果:
引用内容 引用内容
exec sp_executesql N'update [dbo].[Pet]
set [Name] = @0
where ([Id] = @1)
',N'@0 nvarchar(20),@1 int',@0=N'newname3',@1=1

可见,修改后ASP.NET MVC3 + Entity Framework实现了数据按需更新:)

补充说明

[1].一定要有db.Pets.Attach(pet),否则运行会出错,提示:
引用内容 引用内容
Member 'IsModified' cannot be called for property 'Name' because the entity of type 'Pet' does not exist in the context. To add an entity to the context call the Add or Attach method of DbSet<Pet>.


评论: 0 | 引用: 0 | 查看次数: 6316
发表评论
登录后再发表评论!