This is my first Question on stackoverflow, I hope I am doing it right 😉 The search doesn’t provided any hint to my current problem. I am new to ASP.NET MVC 4.
I’ve set up a new ASP.NET MVC 4 Project using Razor-HTML-Engine. I created two Models:
Model Client
[Table("Clients")]
public class Client
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string ContactName { get; set; }
public ICollection<License> Licenses { get; set; }
}
Model License
[Table("Licenses")]
public class License
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string SerialNumber { get; set; }
public ICollection<ActivationHistory> ActivationHistory { get; set; }
}
I read that I will have to make a new Class deriving from DbContext in Order to get this working properly:
public class ClientDbContext : DbContext
{
public DbSet<Client> Clients { get; set; }
public DbSet<License> Licenses { get; set; }
}
In my opinion this gives me:
- two Tables with PrimaryKeys and the association between the Tables (1:N)
- the ability to create a Client Object and use
Client.Licenses.Add()to add a new Element to the Table after using db.SaveChanges() -
a Client with all Licenses using
var t = db.Clients.Single(a => a.Id == 1); -
Am I right so far?
I now added sample data to the Client:
// Get Context
var c = new ClientDbContext();
// Create new License
var n1 = new License();
// Testdata
n1.SerialNumber = "12345";
// Get test Client
var test = c.Clients.Single(v => v.ContactName.Contains("Testclient"));
// Add test License to Client
test.Licenses.Add(n1);
// Save Changes
c.SaveChanges()
Checking the Database, a new Row in the License-Table has been added. There is a foreign Key Client_Id pointing to the correct client Testclient
But if I try to show the information from License on the View, there are no Entries at all:
foreach (var item in Model.Licenses)
{
@Html.DisplayFor(modelItem => item.SerialNumber)
}
I am using the default Controller-Method:
public ActionResult Details(int id = 0)
{
Client client = db.Clients.Find(id);
if (client == null)
{
return HttpNotFound();
}
return View(client);
}
Can anyone please give me a hint what I am doing wrong?
Thank you very much!
You have to mark your navigation properties(Licenses) as
virtual.