我试图在Customer和MembershipType之间的两个Entity Framework代码优先模型之间创建1:1关系。他们的模型是:
Customer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Vidly.Models
{
public class Customer
{
public int Id { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
public bool IsSubscribedToNewsletter { get; set; }
public MembershipType MembershipType { get; set; }
[Display(Name = "Membership Type")]
public byte MembershipTypeId { get; set; }
[Display(Name = "Date of Birth")]
public DateTime? Birthdate { get; set; }
}
}
MembershipType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Vidly.Models
{
public class MembershipType
{
public int Id { get; set; }
public string Name { get; set; }
public short SignupFee { get; set; }
public byte DurationInMonths { get; set; }
public byte DiscountRate { get; set; }
}
}
为什么会这样?在尝试使用Html帮助程序创建下拉框时会导致问题,因为当它保存时,它想要将数据放入MembershipTypeId列,但看起来实体实际上正在使用MembershipType_Id列。
答案 0 :(得分:0)
您可以尝试使用以下代码:
namespace Vidly.Models
{
public class Customer
{
public int Id { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
public bool IsSubscribedToNewsletter { get; set; }
[Display(Name = "Membership Type")]
public byte MembershipTypeId { get; set; }
[Display(Name = "Date of Birth")]
public DateTime? Birthdate { get; set; }
public virtual MembershipType MemshipType { get; set; }
}
public class MembershipType
{
public int Id { get; set; }
public string Name { get; set; }
public short SignupFee { get; set; }
public byte DurationInMonths { get; set; }
public byte DiscountRate { get; set; }
public virtual Customer customer{ get; set; }
}
}
如需了解更多信息和其他相关方法,请参阅以下有用链接:http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx
希望它会有所帮助
由于
KARTHIK