EF Core 2.0.1:
Model:
public class Point { [Obsolete("For ORM(EF) use only", true)] public Point() { } public Point(Distance x, Distance y, Distance z) { _x = x; _y = y; _z = z; } public int Id { get; set; } public Distance X { get => _x; } private Distance _x; public Distance Y { get => _y; } private Distance _y; public Distance Z { get => _z; } private Distance _z; }
Let EF fill in the private fields
public class DomainDbContext : DbContext { public DbSet<Point> Points { get; set; } protected override void OnModelCreating(ModelBuilder builder) {
The final problem is using this controller:
public class PointViewModel // has default parameterless constructcor { public int Id { get; set; } public Distance X { get; set; } public Distance Y { get; set; } public Distance Z { get; set; } }
Use in the controller:
[HttpPost] public async Task<IActionResult> Create([Bind("X,Y,Z")] PointViewModel info) { if (ModelState.IsValid) { var point = new Point(info.X, info.Y, info.Z); _context.Add(point); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(info); }
source share