简体   繁体   中英

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):

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:

客户表

CreditCard.cs (model):

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:

信用卡表

To display the model I simply pass customer from DB to my view:

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM