The ADO.NET Provider for Google Analytics supports Entity Framework which requires C1.EntityFrameworkCore.GoogleAnalytics package to be installed. In this section, the model first approach is used to build an Entity Framework model that maps data tables to classes for simpler access to Google Analytics.
The following code defines the Goals class to map the Accounts datatable.
C# |
Copy Code |
---|---|
public partial class Goals { public string Id { get; set; } public string WebPropertyId { get; set; } public string Kind { get; set; } public string SelfLink { get; set; } public string AccountId { get; set; } public string InternalWebPropertyId { get; set; } public string ProfileId { get; set; } public string Name { get; set; } public bool? Active { get; set; } public double? Value { get; set; } public string Type { get; set; } public DateTime? Created { get; set; } public DateTime? Updated { get; set; } public string ParentLink { get; set; } public string UrlDestinationDetails { get; set; } public string VisitTimeOnSiteDetails { get; set; } public string VisitNumPagesDetails { get; set; } public string EventDetails { get; set; } } |
The next code example defines GoogleAnalyticsContext class to access the Accounts datatable and establish a connection to the Google Analytics service by overriding the OnConfiguring method. This method invokes the UseGoogleAnalytics method of the DbContextOptionsBuilder class to configure the context and establish a connection with the Google Analytics service.
C# |
Copy Code |
---|---|
public partial class GoogleAnalyticsContext : DbContext { public GoogleAnalyticsContext() { Database.AutoTransactionsEnabled = false; } public GoogleAnalyticsContext(DbContextOptions<GoogleAnalyticsContext> options) : base(options) { Database.AutoTransactionsEnabled = false; } public virtual DbSet<Goals> Goals { get; set; } public virtual DbSet<Accounts> Accounts { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseGoogleAnalytics("Key File=********;View Id=**********"); } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Accounts>(entity => { entity.Property(e => e.Id).ValueGeneratedNever(); }); modelBuilder.Entity<Goals>(entity => { entity.HasKey(e => new { e.Id, e.WebPropertyId }); }); OnModelCreatingPartial(modelBuilder); } partial void OnModelCreatingPartial(ModelBuilder modelBuilder); } |
You can now use the LINQ queries to perform different data operations to the mapped classes as demonstrated in the code below.
C# |
Copy Code |
---|---|
static void Select() { Console.WriteLine("Query all Goals..."); using (var context = new GoogleAnalyticsContext()) { foreach (var goal in context.Goals) { Console.WriteLine($"{goal.Id} - {goal.Name} - {goal.SelfLink} - {goal.Created} - {goal.Updated}"); } } } |