2017-02-20 62 views
1

我使用實體框架代碼首先,我需要將對象寫入數據庫並出現一個奇怪的問題,這讓我認爲我的實體模型可能是錯誤的。EF代碼優先:帶有子對象交叉關係的模型問題

的對象包括位置類型2子對象:

var request = new Request(); 
request.StartPosition = new Position(); 
request.EndPosition = new Position(); 
_context.Requests.Insert(request); 

這裏是我的模型:

[Table("Requests")] 
public class Request 
{ 
    [Key] 
    public Guid Id { get; set; } 

    public Guid ProductId { get; set; } 


    public virtual int PositionId { get; set; } 

    [ForeignKey("PositionId")] 
    public virtual Position StartPosition { get; set; } 

    [ForeignKey("PositionId")] 
    public virtual Position DestinationPosition { get; set; } 
}//class 


[Table("Positions")] 
public class Position 
{ 
    [Key] 
    public int Id { get; set; } 

    public double X { get; set; } 

    public double Y { get; set; } 

    public virtual ICollection<Request> Requests { get; set; } 


    public Position() 
    { 
     Requests = new List<Request>(); 
    } 
} 

這是我收到異常: {「參照完整性約束衝突。一個相關的角色有多個不同的價值主體。「}

+0

您的每個職位是否只有一個請求主體?更改公共虛擬ICollection 請求{get;組; }到公共虛擬請求請求{get;組;}? – Sami

回答

1

我相信你的課堂設計可能看起來像這樣...

[Table("Requests")] 
public class Request 
{ 
    [Key] 
    public Guid Id { get; set; } 

    public Guid ProductId { get; set; } 


    public virtual int StartPositionId { get; set; } 

    public virtual int DestinationPositionId { get; set; } 

    [ForeignKey("StartPositionId")] 
    public virtual Position StartPosition { get; set; } 

    [ForeignKey("DestinationPositionId")] 
    public virtual Position DestinationPosition { get; set; } 
} 


[Table("Positions")] 
public class Position 
{ 
    [Key] 
    public int Id { get; set; } 

    public double X { get; set; } 

    public double Y { get; set; } 

    public virtual ICollection<Request> StartPositionRequests { get; set; } 

    public virtual ICollection<Request> DestinationPositionRequests { get; set; } 

    public Position() 
    { 
     StartPositionRequests = new List<Request>(); 
     DestinationPositionRequests = new List<Request>(); 
    } 
} 

加你DbContext可能需要一些額外的信息來定義關係。在EF Core上,這可以工作:

public class MyDbContext : DbContext 
{ 
    public DbSet<Request> Requests { get; set; } 
    public DbSet<Position> Positions { get; set; } 

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 
    { 
     optionsBuilder.UseSqlServer(@"..."); 
    } 

    protected override void OnModelCreating(ModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Position>().HasMany(x => x.StartPositionRequests).WithOne(x => x.StartPosition).OnDelete(DeleteBehavior.Restrict); 
     modelBuilder.Entity<Position>().HasMany(x => x.DestinationPositionRequests).WithOne(x => x.DestinationPosition).OnDelete(DeleteBehavior.Restrict); 
    } 
}