【发布时间】:2011-08-11 23:41:24
【问题描述】:
再次使用无法更改的旧数据库并使用带有 Fluent API 的 Entity Framework 4.1 仅读取数据。
public class Client
{
[Key]
public int ClientID { get; set; }
public string Name { get; set ;}
public virtual ICollection<Phone> Phones { get; set; }
}
public class Phone
{
[Key]
public int PhoneID { get; set; }
public string Number { get; set; }
public virtual Client Client { get; set; }
}
public class ClientPhone
{
[Key]
[Column(Order=0)]
public int ClientID { get; set; }
[Key]
[Column(Order=1)]
public int PhoneID { get; set; }
}
我希望客户端有很多电话,但电话应该只有一个可选的客户端。 注意:电话应该只有 0|1 个客户端。我不想要多对多。 所以我尝试了以下方法:
modelBuilder.Entity<Client>()
.HasMany(c => c.Phones)
.WithOptional(p => p.Client)
.Map(m =>
{
m.MapKey("ClientID");
m.ToTable("ClientPhone");
});
modelBuilder.Entity<Phone>()
.HasOptional(p => p.Client)
.WithMany(c => c.Phones)
.Map(m =>
{
m.MapKey("PhoneID");
m.ToTable("ClientPhone");
});
我尝试了几种排列,通常会收到关于“类型中的每个属性名称必须是唯一的”的错误。
感谢您的帮助。
用答案编辑
这是我对实体类所做的修改。可以从一个客户端导航到多个电话以及从一个电话到一个客户端,但您必须通过 ClientPhone 连接表。
[Table("Client")]
public class Client
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ClientID { get; set; }
public string Name { get; set ;}
public virtual ICollection<Phone> Phones { get; set; } // Client has * Phones
}
[Table("Phone")]
public class Phone
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PhoneID { get; set; }
public string Number { get; set; }
public virtual Client Client { get; set; } // Phone has 0|1 Client
}
[Table("ClientPhone")]
public class ClientPhone
{
// Removed the Key attribute
public int ClientID { get; set; }
[Key] // Left the Key on the 0|1 side
[ForeignKey("Phone")]
public int PhoneID { get; set; }
public virtual Client Client { get; set; } // One Client
public virtual Phone Phone { get; set; } // One Phone
}
【问题讨论】:
-
您的表是如何定义的?数据库中有哪些表,配置了哪些关系?如果数据库包含多对多和联结表,则不能将其映射为一对多。
标签: entity-framework entity-framework-4.1 ef-code-first