asp.net-mvc-3 - EF 4.1-模型关系

标签 asp.net-mvc-3 entity-framework-4 entity-relationship ef-code-first entity-framework-4.1

我正在尝试使用EF 4.1的RC版本创建一个快速的ASP.NET MVC 3应用程序。我有两个模型:

public class Race
{
    public int RaceId { get; set; }
    public string RaceName { get; set; }
    public string RaceDescription { get; set; }
    public DateTime? RaceDate { get; set; }
    public decimal? Budget { get; set; }
    public Guid? UserId { get; set; }
    public int? AddressId { get; set; }

    public virtual Address Address { get; set; }
}


public class Address
{
    public int AddressId { get; set; }
    public string Street { get; set; }
    public string StreetCont { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }

    public virtual Race Race { get; set; }
}

尝试插入新的Race时出现以下错误:

Unable to determine the principal end of an association between the types 'rcommander.Models.Race' and 'rcommander.Models.Address'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.



它不应该自动将RaceId识别为Races表的主键,而将AddressId识别为Addresses表的FK吗?我想念什么吗?

谢谢!

最佳答案

这里的问题似乎是EntityFramework无法识别前键在哪里,因为您在两个对象中都持有交叉引用。不确定要达到的目标时,我可能会建议如下:

public class Race
{
  public int RaceId { get; set; }
  public string RaceName { get; set; }
  public string RaceDescription { get; set; }
  public DateTime? RaceDate { get; set; }
  public decimal? Budget { get; set; }
  public Guid? UserId { get; set; }

  public int? AddressId { get; set; }
  public virtual Address Address { get; set; }
}

public class Address
{
  public int AddressId { get; set; }
  public string Street { get; set; }
  public string StreetCont { get; set; }
  public string City { get; set; }
  public string State { get; set; }
  public string ZipCode { get; set; }
}

在第二实体中跳过对种族的引用。

关于asp.net-mvc-3 - EF 4.1-模型关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5352059/

相关文章:

sql - 在一列中存储多个标签

asp.net-mvc-3 - 在 MVC3 中添加有关打印功能的数据

c# - MVC3 中的角色管理

c# - 通过匿名类型更新数据库?

entity-framework - 什么是实体?为什么叫实体?

eclipse - 包含与引用之间的ECore有什么区别?

c# - 为 MVC 3 实现一点 IOC

jquery - Textarea 没有在 jQuery 中获取更新的文本

asp.net - Entity Framework : Insists on adding new entity in many-to-many instead of re-using existing FK

domain-driven-design - DDD : keep a link to an entity inside an aggregate root, 仅用于报告