[英]Fetch external API using .NET with basic authentication and store data in SQL Server database using EF Core
I'm not getting the data into my SQL Server database.我没有将数据放入我的 SQL 服务器数据库。 Hope someone can guide me.希望有人能指导我。 Thanks.谢谢。
In Visual Studio 2022:在 Visual Studio 2022 中:
Program
: Program
:
using APItoSQL1.Model;
using System.Net.Http.Headers;
async Task<List<Party>> FetchParties()
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "username:password");
var response = await client.GetAsync("url");
response.EnsureSuccessStatusCode();
var data = await response.Content.ReadAsAsync<List<Party>>();
return data;
}
async Task SaveParties(List<Party> parties)
{
using (var context = new MyDbContext())
{
context.Parties.AddRange(parties);
await context.SaveChangesAsync();
}
}
var parties = await FetchParties();
await SaveParties(parties);
}
My DbContext
:我的DbContext
:
using Microsoft.EntityFrameworkCore;
using System.Data.Entity;
using System;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using System.Data.SqlClient;
using DbContext = Microsoft.EntityFrameworkCore.DbContext;
namespace APItoSQL1.Model
{
public class MyDbContext : DbContext
{
public System.Data.Entity.DbSet<Party> Parties { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string connectionString = @"Server="myservername";Initial Catalog="myDBname";Integrated Security=True";
}
}
}
Class Party
: Class Party
:
using System.Xml.Serialization;
namespace APItoSQL1.Model
{
[XmlRoot(ElementName = "parties")]
public class Party
{
[XmlElement(ElementName = "id")]
public int Id { get; set; }
[XmlElement(ElementName = "isOrganization")]
public bool IsOrganization { get; set; }
[XmlElement(ElementName = "primeName")]
public string PrimeName { get; set; }
[XmlElement(ElementName = "email")]
public string Email { get; set; }
[XmlElement(ElementName = "givenName")]
public string GivenName { get; set; }
[XmlElement(ElementName = "phone")]
public string Phone { get; set; }
}
}
Have I missed something?我错过了什么吗? I'd appreciate any help on this.我很感激这方面的任何帮助。
Thanks in advance.提前致谢。
You are mixing "classic" Entity Framework and EF Core:您正在混合使用“经典”实体框架和 EF Core:
Remove the reference to EntityFramework from your project, and remove this using:从您的项目中删除对 EntityFramework 的引用,并使用以下方法删除它:
using System.Data.Entity;
public DbSet<Party> Parties { get; set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.