我有兩個表,一個用於客戶,另一個用於信用卡,並且它們之間存在簡單的一對一關係(這不是真正的數據,它是隻是爲了學習目的)。簡單的一對一關係實體框架代碼優先
即使沒有錯誤和數據在數據庫中,我不能顯示任何客戶的信用卡信息。
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
表:
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
表:
要顯示的模式,我只是從數據庫傳遞客戶我的看法:
控制器:
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);
}
}
查看:
@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)
種子初始化測試數據
public class SchemaDBInitializer : DropCreateDatabaseAlways<SchemaDBContext>
{
protected override void Seed(SchemaDBContext context)
{
var customers = new List<Customer>
{
new Customer
{
CreditCard = null,
Email = "[email protected]",
Id = 1,
Password = "carsonPass",
Username = "carsonUser",
FirstName = "Alexander",
Surname = "Carson"
},
new Customer
{
CreditCard = null,
Email = "[email protected]",
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();
}
}
你需要證明你的控制器代碼。 –
@StephenMuecke我編輯了這個問題並添加了控制器 – Higeath
不確定該'Login()'方法對創建或編輯'User'或'CreditCard'做了什麼。 –