实体框架:将具有关联关系的两个模型同时添加到我的数据库

时间:2018-12-04 18:35:38

标签: asp.net-mvc entity-framework entity-framework-6

我正在尝试使用Entity Framework代码优先方法向数据库中添加一些数据。

这是我的代码:

Member member = new Member
                {
                     ...
                     Cards = new List<Card>() {new Card {  Number = model.CartBankNumber, RegisterTime = DateTime.Now, Status = CardStatus.Verifying }  },
                };
db.Member.Add(member);
await db.SaveChangesAsync();

这是我的Member模型班:

public class Member
{
    ...
    public Member()
    {
        Cards = new List<Card>();
    }

    [Display(Name = "Cards", ResourceType = typeof(Resources))]
    public virtual ICollection<Card> Cards{ get; set; }
}

Card模型类:

public class Card
{
    ...
    [Display(Name = "Id", ResourceType = typeof(Resources))]
    public int Id { get; set; }

    [ForeignKey("Member")]
    public string MemberId { get; set; }

    public virtual Member Member { get; set;}
}

为什么MemberId为空?

Card Table

0 个答案:

没有答案