79237839

Date: 2024-11-29 17:03:53
Score: 1
Natty:
Report link

I know it's been a while but I solve this with the next approach for Entity Framework 6:

First don't let MySql to solve your identitys, only mark your property as Key

[Key]
//[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }

Then when you are saving, detect if the entity you are persisting is new, if so, assign the Guid by yourself, I wrote a recursive function in order to get inside the lists within my object and assign the Id of each element (I'm using and EntityBase class) applying Reflections

private void SetIds(object entity)
{
    try
    {
        if (entity == null) return;
        Type objType = entity.GetType();
        PropertyInfo[] properties = objType.GetProperties();
        foreach (PropertyInfo property in properties)
        {
            object propValue = property.GetValue(entity, null);
            var elems = propValue as IList;
            if (elems != null)
            {
                foreach (var item in elems)
                {
                    SetIds(item);
                }
            }
            else
            {
                if (property.Name == "Id" && (Guid)property.GetValue(entity) == new Guid())
                {
                    property.SetValue(entity, Guid.NewGuid());
                }
            }
        }
    }
    catch (Exception)
    {
    }
}
Reasons:
  • Blacklisted phrase (1): I know it's been
  • Long answer (-1):
  • Has code block (-0.5):
  • Unregistered user (0.5):
  • Low reputation (1):
Posted by: Jeronimo Sampedro