简体   繁体   中英

Entity Framework find foreign key value and update row

I have 2 tables User and Connections . When a User logs in, I want to store the connection and update the row if the user is existing or create if not in the connection table.

public class UserContext : DbContext
{
    public UserContext(DbContextOptions<UserContext> options) : base(options) { }

    public DbSet<User>? Users { get; set; }
    public DbSet<Connection>? Connections { get; set; }
}

public class User
{
    [Key]
    [Required]
    public string? UserName { get; set; }
    public string? Password { get; set; }
    public string? Email { get; set; }
    public DateOnly Date { get; set; }
    public int? ChessScore { get; set; }
    public string? Group { get; set; }
    [Required]
    public ICollection<Connection>? Connections { get; set; }
}

public class Connection
{
    [Required]
    public string? ConnectionID { get; set; }
    [Required]
    public string? UserAgent { get; set; }
    [Required]
    public bool Connected { get; set; }
    ( **Foreign key column** )            <---- query this column
}

My question is this, how would I be able to query foreign key column in Connection ( Username ) and update the row if the specific value is found?

My code now

if (user == null)
{
    user = new User
               {
                   UserName = name,
                   Connections = new List<Connection>()
               };
    db.Users.Add(user);
}

// var result1 = db.Users.Include(m => m.Connections);
            
var result = db.Connections.SingleOrDefault(b => b.UserName == name);

if (result1 != null)
{
    result.ConnectionID = Context.ConnectionId;
    result.UserAgent = Context.GetHttpContext()?.Request.Headers["User-Agent"];
    result.Connected = true;
}
else
{
    user.Connections.Add(new Connection
                {
                    ConnectionID = Context.ConnectionId,
                    UserAgent = Context.GetHttpContext()?.Request.Headers["User-Agent"],
                    Connected = true
                });
}

db.SaveChanges();

I can't add Username { get; set; } Username { get; set; } Username { get; set; } to the model without it complaining about shadow state and failing (make sense to why it does it)

Try the following code. Idea is to load user with it's connections - normal EF flow.

var user = db.Users
  .Include(u => u.Connections) // you can apply filter here
  .Where(u => u.UserName = name)
  .FirstOrDefault();

if (user == null)
{
    user = new User
    {
        UserName = name,
        Connections = new List<Connection>()
    };
    db.Users.Add(user);
}

var connection = user.Connections.FirstOrDefault();
if (connection == null)
{
    connection = new Connection();
    user.Connections.Add(connection);
}

connection.ConnectionID = Context.ConnectionId;
connection.UserAgent = Context.GetHttpContext()?.Request.Headers["User-Agent"];
connection.Connected = true;

db.SaveChanges();

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