Táuròs
C# Model with EF Code First
I read something about interceptors would that be the right approach?
https://khalidabuhakmeh.com/entity-framework-core-5-interceptors
21 replies
C# Model with EF Code First
ok the Controller Action für PUT is this one
[HttpPut("{Id}")]
[ProducesResponseType(204)]
[ProducesResponseType(400)]
[ProducesResponseType(404)]
public IActionResult Update(Guid Id, [FromBody] EditDeploymentDataDto body)
{
if (body == null)
return BadRequest(ModelState);
if (!_deploymentInterface.CheckDeploymentById(Id))
return NotFound();
var deploymentMap = _mapper.Map<DeploymentModel>(body);
if (!ModelState.IsValid)
return BadRequest(ModelState);
if (!_deploymentInterface.UpdateDeployment(deploymentMap))
{
ModelState.AddModelError("", "Something went wrong");
return StatusCode(500, ModelState);
}
return Ok("Deployment wurde geändert");
}
This is the Repository
public bool UpdateDeployment(DeploymentModel deployment)
{
_context.Update(deployment);
return SaveChanges();
}
And this is the Interface
bool UpdateDeployment(DeploymentModel deployment);
21 replies
C# Model with EF Code First
The Test Model is looking like this
public class TestModel : BaseModel
{
[Column(Order = 2)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid TemplateId { get; set; }
[Column(Order = 3)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid VirtualMachineId { get; set; }
[Column(Order = 4)]
public string Status { get; set; }
[Column(Order = 5)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string JSONData { get; set; }
public TemplateModel Template { get; set; }
public VirtualMachineModel VirtualMachine { get; set; }
}
21 replies
✅ Dataannotations
And this is the Function in the DataContext Class
private void OnModelCreatingAddDefaultSqlValues(ModelBuilder modelBuilder)
{
var assemblyName = "SelfService.Portal.Core.API";
var nameSpace = "SelfService.Portal.Core.API.Models";
var asm = Assembly.Load(assemblyName);
List<Type> types = asm.GetTypes().Where(p => p.Namespace == nameSpace).ToList();
var dbSets = typeof(DataContext).GetProperties().Where(p => p.PropertyType.Name.ToLower().Contains("dbset")).ToList();
List<Type> dbSetTypes = new List<Type>();
foreach (PropertyInfo pi in dbSets)
{
dbSetTypes.Add(pi.PropertyType.GetGenericArguments()[0]);
}
foreach (Type t in types)
{
if (typeof(BaseModel).IsAssignableFrom(t) && t.Name != nameof(BaseModel) && dbSetTypes.Contains(t))
{
var properties = t.GetProperties().ToList();
foreach (var p in properties)
{
var att = p.GetCustomAttribute<DefaultValueSqlAttribute>();
if (att != null)
{ modelBuilder.Entity(t).Property(p.Name).HasDefaultValueSql(att.DefaultValueSql);
}
}
}
}
}
17 replies