实体框架一对一的关系 [英] Entity framework one to one relationship
问题描述
我有一个客户表和会员类型
客户和会员类型表之间有一对一的关系
客户表有外国人会员资格表的关键。
我有一个相当混乱的代码,但在客户表中创建外键工作正常。
这是客户表的类
I have a table of customers and Membershiptype
There is one to one relationship between customers and membershiptype table
customer table has foreign key of membershiptype table.
I have a code which is quite confusing but works fine to create a foreign key in customers table.
This is class for customer table
public class Customer
{
public int Id { get; set; }
[Required(ErrorMessage="Please Enter Customer's name")]
[StringLength(255)]
public string Name { get; set; }
public bool IsSubscribedToNewsLetter { get; set; }
public MembershipType MembershipType { get; set; }
[Display(Name = "Date of Birth")]
[Min18YearsIfAMember]
public DateTime? Birthdate { get; set; }
[Display(Name="MembershipType")]
public byte MembershipTypeID { get; set; }
}
}
和membership类型表的类是
and the class for membershiptype table is
public class MembershipType
{
public byte Id { get; set; }
public string Name { get; set; }
public short SignUpFee { get; set; }
public byte DurationInMonths { get; set; }
public byte DiscountRate { get; set; }
public static readonly byte unknown = 0;
public static readonly byte PayAsYouGo = 1;
}
}
我的尝试:
互联网上一对一关系中的大多数tutoirals都使用虚拟,并且不使用上面的stretegy来创建forign键
学生表持有studentaccount表的密钥。并且正在使用虚拟。
What I have tried:
This most of the tutoirals in internet for one to one relationship use virtual and do not use the above stretegy for creating the forign key
the students table is holding the key for studentaccount table. and is using virtual.
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public virtual StudentAccount StudentAccount { get; set; }
}
学生账户表
The student accounts table
public class StudentAccount
{
public int Id { get; set; }
public string Name { get; set; }
public int Amount { get; set; }
[Required]
public virtual Student Student { get; set; }
}
这些一对一关系的两种方法有什么区别。以及它们如何在映射外键时起作用。
What is the difference between two methods for these one to one relationships. and how these works in mapping the foreign key.
推荐答案
请参考此链接。它可能对你有帮助。
[ ^ ]
Please refer this link. It may help you.
Configure One To One Relationship In Entity Framework Using Code First Approach[^]
这篇关于实体框架一对一的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!