简体   繁体   English

简单的一对一关系实体框架代码优先

[英]Simple one-to-one relationship Entity Framework code-first

I have two tables, one for customers and one for creditcards, and there is a simple one-to-one relationship between them (this isn't real data it is just for learning purposes). 我有两个表,一个用于客户,一个用于信用卡,并且它们之间存在简单的一对一关系(这不是真正的数据,仅用于学习目的)。

Even though there are no errors and data is in the database, I can't display any credit card info for customers. 即使数据库中没有错误和数据,我也无法为客户显示任何信用卡信息。

Customer.cs (model): Customer.cs (型号):

public class Customer
{
    [Key]
    public int Id { set; get; }
    public string Username { set; get; }
    public string Password { set; get; }
    public string FirstName { set; get; }
    public string Surname { set; get; }
    public string Email { get; set; }
    public CreditCard CreditCard { get; set; }
}

Customer table: Customer表:

客户表

CreditCard.cs (model): CreditCard.cs (型号):

public class CreditCard
{
    [Key, ForeignKey("Customer")]
    public int Id { get; set; }
    public string NameOnCard { get; set; }
    public string CardNumber { get; set; }
    public DateTime ExpiryDate { get; set; }
    public string CCV { get; set; }
    public Customer Customer { get; set; }
}

CreditCards table: CreditCards表:

信用卡表

To display the model I simply pass customer from DB to my view: 要显示模型,我只需将客户从DB传递到我的视图:

Controller: 控制器:

public class AuthenticationController : Controller
{
    private SchemaDBContext db = new SchemaDBContext();
    public ActionResult Login()
    {
        User user = new User();
        return View(user);
    }

    [HttpPost]
    public ActionResult Login(User user)
    {
        Customer customer = new Customer();
        if (ModelState.IsValid)
        {
            customer = db.Customers.FirstOrDefault(u => u.Username.Equals(user.Username) && u.Password.Equals(user.Password));
            if (customer!=null)
            {
                FormsAuthentication.SetAuthCookie(user.Username, false);
                return View("test", customer);
            }
            else
            {
                ModelState.AddModelError("", "Login data is incorrect!");
            }
        }
        return View(customer);
    }
}

View: 视图:

@using MVC_COMP1562.Models
@model Customer

@Html.DisplayFor(model => model.Username)
@Html.DisplayFor(model => model.Password)
@Html.DisplayFor(model => model.FirstName)
@Html.DisplayFor(model => model.Surname)
@Html.DisplayFor(model => model.Email)
@Html.DisplayFor(model => model.CreditCard.NameOnCard)
@Html.DisplayFor(model => model.CreditCard.CardNumber)
@Html.DisplayFor(model => model.CreditCard.CCV)

Seed that initializes test data 用于初始化测试数据的种子

 public class SchemaDBInitializer : DropCreateDatabaseAlways<SchemaDBContext>
    {
        protected override void Seed(SchemaDBContext context)
        {
            var customers = new List<Customer>
            {
                new Customer
                {
                    CreditCard = null,
                    Email = "carsonalexander@gmail.com",
                    Id = 1,
                    Password = "carsonPass",
                    Username = "carsonUser",
                    FirstName = "Alexander",
                    Surname = "Carson"
                },
                new Customer
                {
                    CreditCard = null,
                    Email = "alonsomeredith@gmail.com",
                    Id = 2,
                    Password = "alonsoPass",
                    Username = "alonsoUser",
                    FirstName = "Meredith",
                    Surname = "Alonso"
                }
            };

            customers.ForEach(s => context.Customers.Add(s));
            context.SaveChanges();

            var creditcards = new List<CreditCard>
            {
                new CreditCard
                {
                    CardNumber = "1234 3456 7890 1111",
                    CCV = "111",
                    Customer = customers[0],
                    ExpiryDate = new DateTime(2018, 04, 01),
                    Id = 1,
                    NameOnCard = "Alexander Carson"
                },
                new CreditCard
                {
                    CardNumber = "2222 0000 1234 6877",
                    CCV = "222",
                    Customer = customers[1],
                    ExpiryDate = new DateTime(2019, 05, 01),
                    Id = 2,
                    NameOnCard = "Meredith Alonso"
                }
             };

            creditcards.ForEach(s => context.CreditCards.Add(s));
            context.SaveChanges();

        }
    }

If there is anybody else struggling with the same problem I have had. 如果有其他人在解决我遇到的同样问题。

Thanks to Gert Arnold I have figured it out since I'm not actually assigning any data to objects children objects which I thought in Entity Framework was automatic. 感谢Gert Arnold我已经弄明白了,因为我实际上并没有将任何数据分配给对象子对象,我认为它在Entity Framework中是自动的。

The answer is lazy loading. 答案是延迟加载。

eg 例如

Whenever we use in our model class another model as a relationship declare it virtual and now everything will work otherwise you have to manually load the data for those objects when you fetch them from the database. 每当我们在模型类中使用时,另一个模型作为关系将其声明为虚拟,现在一切都会工作,否则当您从数据库中获取这些对象时,您必须手动加载这些对象的数据。

public class CreditCard
{
    [Key, ForeignKey("Customer")]
    public int Id { get; set; }
    public string NameOnCard { get; set; }
    public string CardNumber { get; set; }
    public DateTime ExpiryDate { get; set; }
    public string CCV { get; set; }
    public virtual Customer Customer { get; set; } //<--- Here virtual
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架代码优先方法一对一流利的api映射 - Entity Framework code-first approach one-to-one fluent api mapping 一对一关系实体框架 - One-to-one relationship Entity Framework 实体框架一对一关系,其中一个是可选的抛出错误 - Entity Framework one-to-one relationship with one being optional throws error 通过具有多对多关系的实体框架代码优先方法为 SQL Server 播种 - Seeding SQL Server by Entity Framework code-first approach with many-to-many relationship 使用实体框架的代码优先方法在ASP.NET MVC应用程序中缺少外键关系 - Foreign key relationship missing in ASP.NET MVC app using code-first approach with Entity Framework 在asp.net实体框架中以一对一的关系使两个模型彼此了解 - make both models aware of each other with a one-to-one relationship in asp.net entity framework 实体框架一对多关系代码首先是asp .net mvc 5和jquery autocomplete - Entity framework one to many relationship code first asp .net mvc 5 and jquery autocomplete 如何使用ADO.NET实体框架代码优先创建一对多关系? - How to create a one to many relationship using ADO.NET Entity Framework Code First? 实体框架代码第一个一对多关系使用Web API返回数据 - Entity Framework Code First One to Many relationship return data using web api 表列的实体框架枚举属性(代码优先方法) - Entity Framework enum attribute to table column (code-first approach)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM