How to take the Schema of a Model in a Dbcontext made in the Entity Framework Core

Asked

Viewed 55 times

1

Hello, I’m starting to work with Efcore and I’m doing an Override on the method SaveChanges() so that whenever there is a manipulation of the bank I can log this manipulation. My problem is that I am working with Schemas in my bank and do not know how to capture the same of a EntityEntry. My code is like this:

public partial class MyContext : DbContext
{
    // construtores...
    // models
    // ...

    public int SaveChanges(int userId)
    {
        var snapshots = ChangeTracker.Entries().ToList();
        var now = DateTime.UtcNow;

        foreach (var s in snapshots)
        {
            var entityName = s.Entity.GetType().Name;
            var schemaName = ""; // como pego isso aqui ?
            var primaryKey = getKey(s);
            var actionName = s.State.ToString();

            var obj = new Dictionary<string, string>();

            var props = s.OriginalValues.Properties
                                        .Select(x=> x.Name).ToList();

            foreach (var prop in props)
            {
                var originalValue = s.OriginalValues[prop].ToString();
                var currentValue = s.CurrentValues[prop].ToString();

                if (originalValue != currentValue)
                    obj.Add(prop, currentValue.ToString());
            }

            Log log = new Log()
            {
                Acao = $"({actionName}) {schemaName}.{entityName}",
                Registro = JsonConvert.SerializeObject(obj)
            };

            Log.Add(log);

        }

        return base.SaveChanges();
    }

    public override int SaveChanges()
    {
        return SaveChanges(0);
    }

    public virtual int getKey(EntityEntry entity)
    {
        var keyName = Model.FindEntityType(entity.GetType())
                           .FindPrimaryKey().Properties
                           .Select(x => x.Name).Single();

        return (int)entity.GetType().GetProperty(keyName).GetValue(entity, null);
    }

All my models are structured as in the example below:

[Table("Foo", Schema = "Bar")]
public partial class Foo
{
    // ...
}

How can I know which Entity Schema I am working on?

1 answer

1


It has these two ways, one referring to the instance of a class and the other to the class type:

Example:

[Table("Login", Schema = "dbo")]
public class Login
{
    [Key]       
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    [MaxLength(50)]
    public string UserName { get; set; }

    [Required]
    [MaxLength(150)]
    public string Email { get; set; }
}
  • By the instance:

    Login lg = new Login();
    TableAttribute tableAttribute  = (TableAttribute)lg.GetType()                   
        .GetCustomAttributes(typeof(TableAttribute))
        .FirstOrDefault();
    tableAttribute.
    
  • By the type of a class:

    TableAttribute tableAttribute = (TableAttribute)typeof(Login)
         .GetCustomAttributes(typeof(TableAttribute))
        .FirstOrDefault();
    

Note: use both namespace:

  • using System.ComponentModel.DataAnnotations.Schema;
  • using System.Reflection;

After reflection:

tableAttribute.Schema
tableAttribute.Name

References

Online Example

  • 1

    thank you very much Kra, I am "beginner" in csharp and even more with Efcore, helped me a lot!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.