1

我有两个实体:

public class Tournament
{
    [Key]
    public Int32 Id { get; set; }
    public string Name { get; set; }

    public virtual TournamentSite Site { get; set; }
}

public class TournamentSite
{
    [Key]        
    public Int32 Id { get; set;}
    public string Name { get; set; }
}

在 DbContext 中:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Entity<Tournament>()
                    .HasRequired<TournamentSite>(t => t.Site)
                    .WithRequiredDependent()
                    .Map(p => p.MapKey("IdSite"));

        base.OnModelCreating(modelBuilder);
}

一切正常,我的意思是当我加载锦标赛时,它会获得具有正确 ID 和名称的 TournamentSite 问题是我想为特定锦标赛更改 TournamentSite。我尝试过这样的事情:

var tournament = dbContext.Tournaments.Find(1); // Get tournament with id 1
tournament.Site.Id = 2;

dbContext.SaveChanges();

我希望在 Tournament 表中,IdSite 字段现在为 2 而不是 1,但无论我做什么,用于将 Tournament 链接到 TournamentSite 的 IdSite 字段始终为 1。

欢迎任何帮助,谢谢。

4

3 回答 3

1

另一种选择是像这样将 IdSite 实际映射到您的 Tournament 对象

public class Tournament
{
    [Key]
    public Int32 Id { get; set; }
    public string Name { get; set; }
    public Int32 TournamentSiteId { get; set;}
    public virtual TournamentSite Site { get; set; }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Entity<Tournament>()
                    .HasRequired<TournamentSite>(t => t.Site)
                    .WithRequiredDependent()
                    .Map(p => p.MapKey("IdSite"));
        modelBuilder.Entity<Tournament>()
                    .Property(p => p.TournamentSiteId)
                    .HasColumnName("IdSite");
        base.OnModelCreating(modelBuilder);
}

现在你应该能够做到这一点

var tournament = dbContext.Tournaments.Find(1); // Get tournament with id 1
tournament.TournamentSiteId = 2;

dbContext.SaveChanges();

瞧!

于 2012-11-12T18:57:31.517 回答
0

您的代码正在尝试更改 的 ID,而TournamentSite不是IdSite. Tournament您需要改为分配Site属性:

var tournament = dbContext.Tournaments.Find(1);
tournament.Site = dbContext.TournamentSites.Find(2);
dbContext.SaveChanges();
于 2012-11-12T18:40:58.367 回答
0

我终于设法做到了,我重做了这样的模型:

public class Tournament
{
    [Key]
    public Int32 Id { get; set; }
    public string Name { get; set; }

    public Int32 IdSite { get; set; }

    [ForeignKey("IdSite")]
    public virtual TournamentSite Site { get; set; }
}

public class TournamentSite
{
    [Key]        
    public Int32 Id { get; set;}
    public string Name { get; set; }
}

在 OnModelCreating 中不需要做任何事情,该函数如下所示:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     base.OnModelCreating(modelBuilder);
}

现在我可以使用:

var tournament = dbContext.Tournaments.Find(1);
tournament.IdSite = 2;

dbContext.SaveChanges();

感谢帮助。

于 2012-11-13T10:32:03.910 回答