LINQ Check exist Username then get that User's ID - entity-framework

I have an Account table:
table Account
(
UserId int identity(1, 1),
UserName nvarchar(20) not null unique,
Password nvarchar(20) not null
)
By using LINQ. Whether I can check exist UserName for an account then. And it's true then get UserId for that account
(I'm use ASP MVC 4 with Entity Framework)

When using Linq to query from DB, I prefer to use query expression, that is closer to SQL notation than Lambda notation.
Given that you have the username:
try {
int userId = (from x in context.Account
where x.UserName == username
select x.UserId).SingleOrDefault());
if (userId > 0){
// user exists
}
else {
// user does not exist
}
}
catch(InvalidOperationException ex){
// has more than one element
}

var user = Context.Accounts.SinlgeOrDefault(user => user.UserName=="yourValue");
if(user!=null)
{
// you can safely access the user properties here
}

Related

Mongodb multiple fields equality check

public long DebitLedgerBalance(string drLedgerId, string transactionId, decimal amount, string userID)
{
var filter = Builders<Transaction>.Filter.Eq(x => x._id, transactionId);
UpdateDefinition<Transaction> update;
update = Builders<Transaction>.Update.Inc(x => x.debitLedgerBalance, amount * -1);
return db.Transaction.UpdateOne(x => x._id == transactionId, update).ModifiedCount;
}
i'm using mongodb driver(v2.11.3) in asp.net core(v3.1) application.
In the code i'm checking equality of transactionId.I also want to check drLederId.
in short i need to check drledgerId and transactionId both.because I want to find a transaction from the database whose _id is transactionId and a ledgerId is drledgerId.and if that found then update balance with use Inc.
so how can i check both fields at a time?

Using go's sqlx to insert record in postgres table with automatic ID generation

I am using sqlx to create a go api.
I want to insert a record in a table named day.
The corresponding go struct is the following
type Day struct {
ID string `db:"id" json:"id"`
Dateday string `db:"dateday" json:"dateday"`
Nameday string `db:"nameday" json:"nameday"`
Holyday bool `db:"holyday" json:"holyday"`
}
In an endpoint for Day creation, will be receiving all fields but the ID via a post request
What method should I use to interact with my db so as to:
a) create the record
b) not need to pass the ID myself and instruct postgres to auto-generate the field.
The table creation statement is the following:
CREATE TABLE IF NOT EXISTS "day" (
"id" SERIAL PRIMARY KEY,
"dateday" date NOT NULL,
"nameday" varchar(10) NOT NULL,
"holyday" boolean NOT NULL
);
I would suggest to override the MarshalJSON method as mentioned below:
func (r Day) MarshalJSON() ([]byte, error) {
root := make(map[string]interface{})
root["dateday"] = r.Dateday
root["nameday"] = r.Nameday
root["holyday"] = r.Holyday
return json.Marshal(root)
}
Ref: https://golang.org/pkg/encoding/json/#example__customMarshalJSON

Get data from SQL table by linq-to-sql using data from collection

I'm using entity framework to connect to database from my application. I have table in SQL, named Orders. It contains such fields as: TransactionId, ParticipantId and is linked to Transactions table which has one to many connection to Participants table. I need to get data from it using List of classes with such properties: TransactionId, ParticipantId, OrganizationId. Linq must meet such conditions: (orders.TransactionId == TransactionId && orders.ParticipantId == ParticipantId && orders.Transaction.Participants.Any(x=> x.Id == OrganizationId)). This should be done by one query, not by multiple, so, please don't recommend foreach or smth like that.
Like #NetMage said, generally we need examples. Assuming that you've got a dbcontext set up, the ask is pretty simple:
public static void GetData(int transactionId, int participantId, int organizationId)
{
using (var db = new MyDbContext())
{
var query =
(
from t in db.Transactions
from o in db.Orders
.Where(w => w.TransactionId == t.TransactionId)
from p in db.Participants
.Where(w => w.TransactionId == t.TransactionId)
where t.TransactionId = transactionId &&
o.ParticipantId = participantId
select new { Order = o, Transaction = t, Participant = p}
);
}
}
Again since we don't have a lot of information here it's hard to do more. You should be able to take it from there. I know I didn't use the organizationId filter, but since I don't know the target shape of the data I'm not sure what the best path would be

linq query to update boolean field in table with where condition

I am trying to update one field in db which is of type Boolean. This is the table structure
usr_id int False
usr_fname nvarchar(50)
usr_lname nvarchar(50)
usr_username nvarchar(50)
usr_password nvarchar(MAX)
usr_email nvarchar(50)
usr_pwdresetstatus bit
This is something I am trying
public int ForGotPassword(string username, string emailid)
{
var result = db.tm_usr_usermaster.Where(m => m.usr_username == username && m.usr_email==emailid).Select(m => m.usr_isactive).SingleOrDefault();
bool isactive = Convert.ToBoolean(result);
if(isactive==false)
{
//Update query
}
else
{
}
I am receiving parameters username and email id if both matches pwdresetstatus should be updated as true. I can write sql equivalent here
Update tablename set pwdresetstatus=true where usr_username==username && usr_email==emailed. I have difficult times to go ahead
I tried this
tm_usr_usermaster users = db.tm_usr_usermaster.FirstOrDefault(x => x.usr_email==emailid && x.usr_username==username);
users.usr_pwdresetstatus = true;
db.SaveChanges();
and working fine. Thank you stephen

How to Add table association in Entity Framework?

I have a table called User, a table called Permission and an association table so Many Users can have many Permissions.
User
ID - PK
Permission
ID - PK
UserPermission
UserID - PK (FK to user)
PermissionID - PK (FK to Permission)
In entity framework how can I add an entry to the association table to link a user to a permission?
I have tried the following with no luck:
var user = _Repository.Users.Single(u => u.ID == someUserID);
var permission = _Repository.Permissions.Single(p => p.ID == somePermissionID);
user.Permissions.Add(permission) //Not working
user.Permission.Attach(permission) //Still not working
_Repository.Save();
Can anyone help?
It should be :
UserPermission obj = new UserPermission { UserID = someUserID, PermissionID = somePermissionID };
_Repository.UserPermissions.AddObject(obj)
_Repository.Save();
Hope this will help.