简体   繁体   中英

Error when referencing entities from ASP.Net MVC project in Azure Function project

I have a ASP.Net MVC project that contains my db entities and my context uses IdentityDbContext applicationuser

public class MyprojectContext : IdentityDbContext<ApplicationUser>

everything works fine connecting and fetching database data!

I also have a azure functions project to perform work and I need to access the db (using entity framework) and fetch different entity data. So I referenced the MVC app in the Azure Function app so I could have all the entities/classes.

But when I try and fetch data into one of the entities 'YogaSpaceEvent' I get the error below, if I create my own entity in the Azure Function code (see code below) it works fine and fetches the data.

I'm guessing it might have something to do with each member fetching data in the MVC app using

IdentityDbContext<ApplicationUser>

and in the Azure Function app I'm only using DbContext????

System.Data.Entity.ModelConfiguration.ModelValidationException: 'One or more validation errors were detected during model generation: PostEventEmail.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.

namespace PostEventEmail
{
public static class PostEventEmail
{
    [FunctionName("PostEventEmail")]
    public static void Run([TimerTrigger("0 */1 * * * *")]TimerInfo myTimer, TraceWriter log)
    {
        log.Info($"C# Timer trigger function executed at: {DateTime.Now}");

        YogaSpaceEvent newEvent = new YogaSpaceEvent(); // references the Asp.Net MVC app entity

        using (var dbContext = new YogabandyContext())
        {
            var ybEvents = dbContext.YogaSpaceEvent.FirstOrDefault();
            log.Info("event id = " + ybEvents.YogaSpaceEventId);
        }          
    }

    // if I uncomment this and use it, it works fine and fetches data
    //public class YogaSpaceEvent
    //{
    //    public int YogaSpaceEventId { get; set; }
    //}

    public partial class YogabandyContext : DbContext
    {
        public YogabandyContext()
            : base("Server=tcp:yoga2017.database.windows.net,1433;Initial Catalog=Yoga2017;Persist Security Info=False;User ID=chuckd;Password=**********!;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;")
        {
        }

        public DbSet<YogaSpaceEvent> YogaSpaceEvent { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //base.OnModelCreating(modelBuilder);
        }
    }

}

}

According to your description, I created my Asp.Net MVC application with ASP.NET Identity to check this issue. I created the YogaSpaceEvent in my MVC project and defined the DBContext as follows:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<YogaSpaceEvent> YogaSpaceEvent { get; set; }

    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public ApplicationDbContext(string connectionString) : base(connectionString, throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

public class YogaSpaceEvent
{
    public int YogaSpaceEventId { get; set; }
    public string YogaSpaceEventName { get; set; }
    public DateTime CreateTime { get; set; }
}

For my Azure Function, I just referenced the MVC project and use the ApplicationDbContext for accessing entities from my database as follows:

public static void Run([TimerTrigger("*/20 * * * * *")]TimerInfo myTimer, TraceWriter log)
{
    log.Info($"C# Timer trigger function executed at: {DateTime.Now}");

    var connString=ConfigurationManager.AppSettings["sqldb-connectionstring"];

    using (var dbContext = new ApplicationDbContext(connString))
    {
        var ybEvents = dbContext.YogaSpaceEvent.FirstOrDefault();
        log.Info("event id = " + ybEvents?.YogaSpaceEventId);
    }
}

local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=AccountName;AccountKey=AccountKey",
    "AzureWebJobsDashboard": "DefaultEndpointsProtocol=https;AccountName=AccountName;AccountKey=AccountKey",
    "sqldb-connectionstring": "Data Source=.\\sqlexpress;Initial Catalog=DefaultConnection;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
  }
} 

It could work on my side. Here is my code sample , you could refer to it. Moreover, your error is strange, you need to check your code or provide a sample project for us to reproduce this issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM