gpt4 book ai didi

c# - 如何在代码优先映射中指定 1-1 关系的主体端

转载 作者:太空宇宙 更新时间:2023-11-03 13:29:33 25 4
gpt4 key购买 nike

我有一个类:

public partial class CanteenTerminal : XTimeEntity
{
public virtual Terminal Terminal { get; set; }
public short TerminalId { get; set; }
}

及其映射类:

public CanteenTerminalMap()
{
// Primary Key
HasKey(t => t.Id);

// Table & Column Mappings
ToTable("CANTEENTERM");
Property(t => t.Id).HasColumnName("TERM_CODEID");

// Relationships
HasRequired(t => t.Terminal)
.WithOptional(t => t.CanteenTerminal);
}

我还有类 Terminal:

public partial class Terminal : XTimeEntity
{
public Terminal()
{
ControllerInterfacePointers = new List<ControllerInterfacePointer>();
TerminalParameters = new List<TerminalParameter>();
}

public string Name { get; set; }
public string Version { get; set; }
public short Enabled { get; set; }
public virtual CanteenTerminal CanteenTerminal { get; set; }
public short CanteenTerminalId { get; set; }
public virtual ICollection<ControllerInterfacePointer> ControllerInterfacePointers { get; set; }
public virtual ICollection<TerminalParameter> TerminalParameters { get; set; }
}

及其映射文件:

public TerminalMap()
{
// Primary Key
HasKey(t => t.Id);

Property(t => t.Name)
.IsRequired()
.HasMaxLength(30);
Property(t => t.Version)
.HasMaxLength(8);

// Table & Column Mappings
ToTable("TERMINAL");
Property(t => t.Id).HasColumnName("TERM_CODEID");
Property(t => t.Name).HasColumnName("TERM_NAME");
Property(t => t.Version).HasColumnName("TERM_VERSION");
Property(t => t.Enabled).HasColumnName("TERM_ENABLED");
Ignore(t => t.MasterId);
Ignore(t => t.IsActive);

HasOptional(t => t.CanteenTerminal)
.WithRequired(t => t.Terminal);
}

每当构建数据模型时,即当我运行测试查询时,我都会收到以下错误。我得到了几个一对一的关系,我只是暂时从实体中删除了这些属性,以避免我还不感兴趣的实体出现错误。

Unable to determine the principal end of an association between the types 'XTime.Data.CanteenTerminal' and 'XTime.Data.Terminal'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

我该如何指定关系的主体端?

最佳答案

这里有一个关于此类问题的很好的例子: http://msdn.microsoft.com/en-us/data/jj591620#RequiredToRequired

这里主键的映射是:

modelBuilder.Entity<OfficeAssignment>()
.HasKey(t => t.InstructorID);

modelBuilder.Entity<Instructor>()
.HasRequired(t => t.OfficeAssignment)
.WithRequiredPrincipal(t => t.Instructor);

我确实必须在示例中添加一个额外的 nav 属性(在 instructor 类中),它似乎工作正常:

// Navigation property 
public virtual OfficeAssignment OfficeAssignment { get; set; }

关于c# - 如何在代码优先映射中指定 1-1 关系的主体端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21130257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com