简体   繁体   中英

Stored procedure still return same result with Entity Framework Core

I have a stored procedure called GetContactsByUserId @userId INT .

I want to call this stored procedure with Entity Framework Core (7.0.0-rc1-final).

The stored procedure return these types in the result:

ContactId INT, ContactName NVARCHAR(200)

I have created in C# the object called - Contact :

[Key]
public int ContactId {get; set;}

public string ContactName {get;set;}

And this DbSet:

public DbSet<Contact> Contacts { get; set; }

I've tried call the stored procedure like this:

_dbContext.Set<Contact>().FromSql("dbo.GetContactsByUserId @userId = {0}", userid);

After first call I get for example 30 rows. I add new records and try again call this procedure with the same parameter and I get 30 rows not 31 rows.

How can I fix this issue?

Are you sure you called _dbcontext.SaveChanges(); after you added new contacts? That is, are you sure they are in the database?

I mocked up a console example using a stored procedure to list contacts and it works as expected. It returns the correct number of contacts the first time as well as after I add additional contacts.

Here is my ListContacts code in case it helps:

    public static List<Contact> ListContacts()
    {
        var contacts = new List<Contact>();           

        using (var db = new AppDbContext())
        {
            var contactsSQL = db.Set<Contact>().FromSql("dbo.GetContacts");

            foreach (var contactSQL in contactsSQL)
            {
                var contact = new Contact();
                contact.ID = contactSQL.ID;
                contact.Name = contactSQL.Name;
                contacts.Add(contact);
            }

            return contacts;
        }
    }

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