【发布时间】:2013-12-12 23:33:07
【问题描述】:
我正在使用 .Net Framework 4.0 开发 Entity Framework Code First (v. 4.4.0.0) C# 库。
我不知道如何设置零对一的关系。我的模型如下:
Talk 只能由一个用户 (StarterUserId) 创建。Talk 只能有一个收件人用户 (RecepientUserId) 或只有一个组 (RecipientGroupId)。
注意:这意味着如果RecipientGroupId不为空,则RecepientUserId为空;如果RecipientGroupId为空,则RecepientUserId不为空。
user 可以是零或 n Talks 的收件人,但 group 可以是零或一个 Talk。
这是谈话课:
[DataContract]
public class Talk
{
[DataMember]
public int TalkId { get; set; }
[DataMember]
public int StarterUserId { get; set; }
[DataMember]
public int? RecipientUserId { get; set; }
[DataMember]
[ForeignKey("RecipientGroup")]
public int? RecipientGroupId { get; set; }
public DateTime DateUtcStarted { get; set; }
[DataMember]
public string DateStarted
{
get
{
return DateUtcStarted.ToString("dd/MM/yyyy HH:mm");
}
set
{
DateUtcStarted = DateTime.Parse(value);
}
}
public User StarterUser { get; set; }
public User RecipientUser { get; set; }
public Group RecipientGroup { get; set; }
}
使用这个 TalkConfiguration 类:
class TalkConfiguration : EntityTypeConfiguration<Talk>
{
public TalkConfiguration()
{
Property(t => t.StarterUserId).IsRequired();
Property(t => t.RecipientUserId).IsOptional();
Property(t => t.RecipientGroupId).IsOptional();
Property(t => t.DateUtcStarted).IsRequired();
Ignore(t => t.DateStarted);
HasRequired(t => t.StarterUser).
WithMany(u => u.TalksStarted).
HasForeignKey(t => t.StarterUserId);
HasOptional(t => t.RecipientUser).
WithMany(u => u.InTalks).
HasForeignKey(t => t.RecipientUserId);
HasOptional(t => t.RecipientGroup).WithOptionalDependent(g => g.GroupTalk);
}
}
这是Group 类:
[DataContract]
public class Group
{
[DataMember]
public int GroupId { get; set; }
[ ... ]
public Talk GroupTalk { get; set; }
}
还有GroupConfiguration 类:
class GroupConfiguration : EntityTypeConfiguration<Group>
{
public GroupConfiguration()
{
[ ... ] // Nothing related to GroupTalk
}
}
通过这些类和配置,我在数据库中得到了这个 Talk 表:
我想让Talk.RecipientGroupId 作为Group.GroupId 的外键。但是这个模型创建了另一个列,Talk.RecipientGroup_GroupId 作为 FOREIGN KEY 到 Group.GroupId。而且,我不希望那样。
我该怎么做?
【问题讨论】:
标签: c# sql entity-framework database-design entity-relationship