EF Code First .SaveChanges更新错误表

时间:2011-03-14 10:38:56

标签: entity-framework asp.net-mvc-3 ef-code-first

我声明了以下表格

namespace RLSBCWebSite.Domain.Entities
{

    [Table( Name = "tblFixtures" )]
    [DisplayColumn( "Date", "Date", false )]
    public class Fixture
    {
        [HiddenInput( DisplayValue = false )]
        [Column( IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert )]
        public int FixtureID { get; set; }

        [Required( ErrorMessage = "Please select Male, Female or Mixed" )]
        public string Gender { get; set; }

    ...... more columns

        public IEnumerable<ValidationResult> Validate( ValidationContext validationContext )
        {
            if (((ScoreFor > 0) || (ScoreAgainst > 0)) && (!String.IsNullOrEmpty( Comments )))
                yield return new ValidationResult( "Please complete either ScoreFor & ScoreAgainst or Comments!", new[] { "Comments" } );
        }
    }
}

我的DbContext如下:

namespace RLSBCWebSite.Domain.Entities
{

    public class RLSBCWebSiteDb : DbContext

    {

        public DbSet<Officer> tblOfficers { get; set; }

        public DbSet<Fixture> tblFixtures { get; set; }

        public DbSet<CompetitionWinner> tblCompetitionWinners { get; set; }

    }
}

我的Web.Config有:

    <connectionStrings>
    <add name="RLSBCWebSiteDb"
        connectionString="data source=MAINPC\SQLEXPRESS;Initial Catalog=RLSBCWebSite;Integrated Security=True"
        providerName="System.Data.SqlClient" />
</connectionStrings>

我的控制器代码是:

        RLSBCWebSiteDb rlsbcWebSite = new RLSBCWebSiteDb();

    [HttpPost]
    public ActionResult CreateFixture(Fixture fixture)
    {
        if (ModelState.IsValid)
        {
            rlsbcWebSite.tblFixtures.Add( fixture );
            rlsbcWebSite.SaveChanges();

            return RedirectToAction( "MensResults", new { id = fixture.MatchDate.Year.ToString() } );
        }

        return View( fixture );
    }

当我尝试保存条目时,在执行.SaveChanges()语句时,我收到一条带有以下错误消息的SQL UpdateException。

  

无效的对象名称'dbo.Fixtures'。

为什么要尝试更新名为Fixtures的表?当然,它应该更新tblFixtures。

1 个答案:

答案 0 :(得分:1)

我认为[Table( Name = "tblFixtures" )]无效,因为Name不是TableAttribute类的属性 - 看起来像这样:

public class TableAttribute : Attribute
{
    public TableAttribute(string tableName);

    public string SchemaName { get; set; }
    public string TableName { get; }
}

因此,以下属性设置应该兼有:

[Table("tblFixtures")]

[Table(TableName = "tblFixtures")]

编辑:但我想知道为什么你没有收到编译错误?

我刚注意到TableAttribute命名空间(在System.Data.Linq.dll程序集中)中有另一个System.Data.Linq.Mapping类,它实际上具有Name属性。也许您的命名空间使用错误。您需要TableAttribute命名空间中的System.ComponentModel.DataAnnotations类(在EntityFramework.dll程序集中)。