Skip to content

Instantly share code, notes, and snippets.

@yuhangch
Last active March 20, 2022 12:44
Show Gist options
  • Save yuhangch/bca2774ee4ede011213731ecf761523b to your computer and use it in GitHub Desktop.
Save yuhangch/bca2774ee4ede011213731ecf761523b to your computer and use it in GitHub Desktop.
EF Core / Postgresql LINQ command is already in progress
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDbContext<TestDb>(options =>
options.UseNpgsql(connectionString).UseLazyLoadingProxies());
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapGet("/", async (TestDb db) =>
{
var result = await db.Cities
.Include(c => c.Point) // Add this row
.Select(
s => new
{
Inherit = s.Point, // work
Point = s.GetPoint(), // not work without Include
}
).ToListAsync();
return Results.Ok(result);
});
app.MapControllers();
app.Run();
public interface ILocation
{
public string GetName();
public double GetX();
public double GetY();
public Point GetPoint();
}
public class BaseLocation
{
[ForeignKey("Point")] public int PointRefId { get; set; }
public virtual Point Point { get; set; }
}
[Table("point")]
public class Point
{
[Key] public int Id { get; set; }
public double X { get; set; }
public double Y { get; set; }
}
[Table("city")]
public class City : BaseLocation, ILocation
{
[Key] public int Id { get; set; }
public string Name { get; set; }
public double GetX()
{
return Point.X;
}
public double GetY()
{
return Point.Y;
}
public Point GetPoint()
{
return Point;
}
public string GetName()
{
return Name;
}
}
class TestDb : DbContext
{
public TestDb(DbContextOptions<TestDb> options) : base(options)
{
}
public DbSet<Point> Points { get; set; }
public DbSet<City> Cities { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment