linq to entity update records to database - asp.net

This is the update code I found:
using (TestDBEntities ctx = new TestDBEntities())
{
//Get the specific employee from Database
Emp e = (from e1 in ctx.Emp
where e1.Name == "Test Employee"
select e1).First();
//Change the Employee Name in memory
e.Name = "Changed Name";
//Save to database
ctx.SaveChanges();
}
Now what I am doing is like this:
using(CRNNSTestEntities crnnsupContext = new CRNNSTestEntities())
{
CPersonalInfo t = ((IQueryable<CPersonalInfo>)Cache["personquery"]).First();
t.Tombstone.Address = Address1.Text;
System.Windows.Forms.MessageBox.Show(crnnsupContext.SaveChanges()+"");
};
which doesn't work. So my question is do I have to write something like CPersonalInfo t = from t in ....
Why doesn't my method doesn't work?
Thanks

You need to get the entity CPersonalInfo t from your crnnsupContext and not from your Cache

You can also attach object to the context before.
More info how to use attach here

can you change this
using (TestDBEntities ctx = new TestDBEntities())
{
//Get the specific employee from Database
Emp e = (from e1 in ctx.Emp
where e1.Name == "Test Employee"
select e1).First();
//Change the Employee Name in memory
e.Name = "Changed Name";
//Save to database
ctx.SaveChanges();
}
into
using (TestDBEntities ctx = new TestDBEntities())
{
//Get the specific employee from Database
Emp e = (from e1 in ctx.Emp
where e1.Name == "Test Employee"
select e1).First();
var entity = ctx.Emp.Find(e);
//Change the Employee Name in memory
entity.Name = "Changed Name";
//Save to database
ctx.SaveChanges();
}

Related

Problems with IDocumentQuery.ExecuteNextAsync()

I have standard lines of code, to fetch data with pagination. It used to work until a month ago, and then stopped. On running ExecuteNextAsync() it stops execution, and displays this following information in Output window:
DocDBTrace Information: 0 : DocumentClient with id 2 disposed.
DocDBTrace Information: 0 : DocumentClient with id 1 disposed.
Not Working Code:
var query =
client.CreateDocumentQuery(
UriFactory.CreateDocumentCollectionUri(databaseId, "TestCollection"), "select c.id from TestCollection c",
new FeedOptions
{
//MaxDegreeOfParallelism=-1,
MaxItemCount = maxItemCount,
PopulateQueryMetrics=true
//RequestContinuation = requestContinuation,
//EnableScanInQuery = true,
//EnableCrossPartitionQuery = true
});
var queryAll = query.AsDocumentQuery();
var results = new List<TDocument>();
while (queryAll.HasMoreResults)
{
try
{
var result = await queryAll.ExecuteNextAsync();
var queryMetrics = result.QueryMetrics;
if (result.ResponseContinuation != null) requestContinuation = result.ResponseContinuation;
//Do something here
}
catch (Exception ex)
{
}
}
For the same client object, Create/Update or fetching all items together is working. So JsonSerializer or DocumentClient object cannot be a problem.
Working code:
var query2 = client.CreateDocumentQuery(
UriFactory.CreateDocumentCollectionUri(databaseId, collectionName), "select * from TestCollection c",
new FeedOptions { MaxItemCount = -1 });
//.Where(l => l.Id == qId);
var testData2= query2.ToList();
This has stopped our services and their development. Any help is appreciated.
Your query is wrong.
UriFactory.CreateDocumentCollectionUri(databaseId, "TestCollection") will already let the SDK know what to query.
If you simply change
select c.id from TestCollection c
to
select c.id from c
It will work. Currently it is failing to resolve the c alias because you also have TestCollection there.
The only reason your other queries that use * are working is because you aren't using the c. there.

Can I generate SQL scripts with ServiceStack OrmLite?

Is it possible to generate SQL scripts using OrmLite without executing it against a database? I would like to load a list of DTOs from a live SqlServer database and output a script to DELETE and INSERT each record.
The provided mini profiler supports logging, but looks like it needs to wrap a real database connection.
This is trivial now that OrmLite extension methods are now mockable by providing your own OrmLiteResultsFilter.
E.g. this ResultsFilter below records every sql statement executed and inherts the behavior from OrmLiteResultsFilter to return empty results:
public class CaptureSqlFilter : OrmLiteResultsFilter
{
public CaptureSqlFilter()
{
SqlCommandFilter = CaptureSqlCommand;
SqlCommandHistory = new List<SqlCommandDetails>();
}
private void CaptureSqlCommand(IDbCommand command)
{
SqlCommandHistory.Add(new SqlCommandDetails(command));
}
public List<SqlCommandDetails> SqlCommandHistory { get; set; }
public List<string> SqlStatements
{
get { return SqlCommandHistory.Map(x => x.Sql); }
}
}
You can wrap this in an using scope to capture each SQL statement without executing them, e.g:
using (var captured = new CaptureSqlFilter())
using (var db = OpenDbConnection())
{
db.CreateTable<Person>();
db.Select<Person>(x => x.Age > 40);
db.Single<Person>(x => x.Age == 42);
db.Count<Person>(x => x.Age < 50);
db.Insert(new Person { Id = 7, FirstName = "Amy", LastName = "Winehouse" });
db.Update(new Person { Id = 1, FirstName = "Jimi", LastName = "Hendrix" });
db.Delete<Person>(new { FirstName = "Jimi", Age = 27 });
db.SqlColumn<string>("SELECT LastName FROM Person WHERE Age < #age",
new { age = 50 });
db.SqlList<Person>("exec sp_name #firstName, #age",
new { firstName = "aName", age = 1 });
db.ExecuteNonQuery("UPDATE Person SET LastName={0} WHERE Id={1}"
.SqlFmt("WaterHouse", 7));
var sql = string.Join(";\n\n", captured.SqlStatements.ToArray());
sql.Print();
}
Which prints out:
CREATE TABLE "Person"
(
"Id" INTEGER PRIMARY KEY,
"FirstName" VARCHAR(8000) NULL,
"LastName" VARCHAR(8000) NULL,
"Age" INTEGER NOT NULL
);
;
SELECT "Id", "FirstName", "LastName", "Age"
FROM "Person"
WHERE ("Age" > 40);
SELECT "Id", "FirstName", "LastName", "Age"
FROM "Person"
WHERE ("Age" = 42)
LIMIT 1;
SELECT COUNT(*) FROM "Person" WHERE ("Age" < 50);
INSERT INTO "Person" ("Id","FirstName","LastName","Age") VALUES (#Id,#FirstName,#LastName,#Age);
UPDATE "Person" SET "FirstName"=#FirstName, "LastName"=#LastName, "Age"=#Age WHERE "Id"=#Id;
DELETE FROM "Person" WHERE "FirstName"=#FirstName AND "Age"=#Age;
SELECT LastName FROM Person WHERE Age < #age;
exec sp_name #firstName, #age;
UPDATE Person SET LastName='WaterHouse' WHERE Id=7
More examples available in CaptureSqlFilterTests.cs
As CaptureSqlFilter is useful I've just added it to OrmLite in this commit which will be in the next v4.0.20 that's now available on MyGet.
Using the DialectProvider directly seems to work well enough for what I need. ToInsertRowStatement takes a IDbCommand paramater, but does not use it so null works.
OrmLiteConfig.DialectProvider = SqlServerOrmLiteDialectProvider.Instance;
var dto = new PersonDTO { Id = Guid.NewGuid(), Name = "Carl" };
var deleteText = SqlServerOrmLiteDialectProvider.Instance.ToDeleteRowStatement(dto);
var insertText = SqlServerOrmLiteDialectProvider.Instance.ToInsertRowStatement((IDbCommand)null, dto);
Is there a better alternative?
I use this to capture the statement and keep running the sentense.
public class CustomOrmLiteExecFilter : OrmLiteExecFilter
{
public override T Exec<T>(IDbConnection dbConn, Func<IDbCommand, T> filter)
{
var holdProvider = OrmLiteConfig.DialectProvider;
var dbCmd = CreateCommand(dbConn);
try
{
var ret = filter(dbCmd);
var pureSQL = holdProvider.MergeParamsIntoSql(dbCmd.CommandText, dbCmd.Parameters.OfType<IDbDataParameter>());
//log or save the SQL Statement
return ret;
}
finally
{
if (OrmLiteConfig.DialectProvider != holdProvider)
OrmLiteConfig.DialectProvider = holdProvider;
}
}
}
and the usage:
OrmLiteConfig.ExecFilter = new CustomOrmLiteExecFilter();
hope this can help you!

Querystring display details

I got this tblDocument table which has a one to many relationship to a couple of other tables. I have created this querystring that displays the content of the document. In this soulution i only display the DocPerson id. What im trying to do is to display the name of the person which is located in the tblPerson table. Can someone help me?
if (!IsPostBack)
{
string strId = Request.QueryString["id"];
int id;
if (int.TryParse(strId, out id))
{
var db = new MyModelContext();
var p = db.tblDocuments.SingleOrDefault(x => x.DocId == id);
if (p != null)
{
lblCaseNr.Text = p.DocNr;
lblPerson.Text = p.DocPerson.ToString();
lblCourt.Text = p.DocCourt.ToString();
lblYear.Text = p.Docyear.ToString();
lblResume.Text = p.DocResume;
lblResult.Text = p.DocResult;
lblLaw.Text = p.DocLaw.ToString();
}
}
}
}
For your LINQ expression, try the following:
var q = from d in db.tblDocuments join p in db.tblPerson
on d.DocId equals p.DocId
where d.DocId == id
select new {d.DocId, p.DocPerson}
If you need to access other fields, simply add them to your select new clause.

Get id of new record in DNN Module

Am new to DNN Module development and using MVC and Linq. Have built a class and controller that allows me to create a record in a table on the database. Can anyone tell me the best way to retrieve the id of the newly created record? The part of the controller for creating the record is below.
class BlockController
{
public void CreateBlock(Block b)
{
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Block>();
rep.Insert(b);
}
}
}
Call to the controller from the code
var bC = new BlockController();
var b = new Block()
{
SectionId = int.Parse(ddlPickSection.SelectedValue),
PlanId = int.Parse(ddlPickPlan.SelectedValue),
BlockName = bId,
BlockDesc = "",
xPos = bX,
yPos = bY,
width = arrBWidths[i],
ModuleId = ModuleId,
CreatedOnDate = DateTime.Now,
CreatedByUserId = UserId,
LastModifiedOnDate = DateTime.Now,
LastModifiedByUserId = UserId,
};
bC.CreateBlock(b);
Thanks
When you submit changes (insert the record in DB) the ID would available in b object:
...
rep.InsertOnSubmit(b);
ctx.SubmitChanges();
int desireID = b.id;

Insert into bridge table entity framework

Hi guys,
I'm learning to climb with EF ,I do have basic understanding of CRUD with EF ,but now I have a table which have a navigation property (Which I suspect is the bridge table) ,so I need to add value into the bridge table ,I think I can do it with navigational property.
Problem Explained:
Original partial DB Diagram
Partial EF Model Diagram
Code I Wrote:
protected void BtnAddUser_Click(object sender, EventArgs e)
{
DBEntities entities = new DBEntities();
var usr = new User();
//I thought I would add an Roles object into usr.UserRoles.Add(usrRoles);
//but UserRoles have only two fields ,RoleTypeId and UserId
//var usrRoles = new Roles()
//{Id=0,RoleDescription="dfdfdf",RoleType="WebSite Admin"};
usr.UserName = TxtbxUserName.Text;
usr.Password = TxtBxPassword.Text;
usr.Email = TxtbxEmail.Text;
usr.CreateDate = DateTime.Now;
usr.LastActivityDate = DateTime.Now;
usr.IsEnabled = true;
//What to Add in the .Add method
usr.UserRoles.Add(
entities.User.AddObject(usr);
int result = entities.SaveChanges();
LblMsg.Text = result == 1 ? "User created successfully." : "An error occured ,please try later.";
entities.Dispose();
}
Update (What I have tried so far):
I fetch "Website Admin" role from roles table and put it into ObjectContext.UserRoles.Add(UserRoleWebsiteAdmin);
So that what I did in the code,
//Fetch WebsiteAdmin from Roles
var userRole = from usrRole in entities.Roles
where usrRole.Id == 1
select usrRole;
usr.UserName = TxtbxUserName.Text;
//same old code of usr.Property = someTextBox
//I have tried to type cast it LinqtoEntities result into Roles
usr.UserRoles.Add((Roles)userRole);
Exception generated
P.S: Let me know if you need more clarification.
Maybe you can use using http://msdn.microsoft.com/en-us/library/yh598w02.aspx and object initializer http://msdn.microsoft.com/en-us/library/bb384062.aspx for better readability so:
using(DBEntities entities = new DBEntities())
{
//Make user object
var user = new User{
UserName = TxtbxUserName.Text,
Password = TxtBxPassword.Text,
Email = TxtbxEmail.Text,
CreateDate = DateTime.Now,
LastActivityDate = DateTime.Now,
IsEnabled = true
};
//Fetch type of Role from Roles table
var userRole = entities.Roles.Where(x=>x.usrRole.Id ==1).Single();
user.UserRoles.Add(userRole);
entities.User.AddObject(user);
int result = entities.SaveChanges();
LblMsg.Text = result == 2 ? "User created succesfully." : "An error occured ,please try later.";
}
Regards
Well thanks guys...
Here what I have done and it works,
DBEntities entities = new DBEntities();
//Make user object
var usr = new User();
//Fetch type of Role from Roles table
var userRole = (from usrRole in entities.Roles
where usrRole.Id == 1
select usrRole).Single();
//copy user related info from textboxes
usr.UserName = TxtbxUserName.Text;
usr.Password = TxtBxPassword.Text;
usr.Email = TxtbxEmail.Text;
usr.CreateDate = DateTime.Now;
usr.LastActivityDate = DateTime.Now;
usr.IsEnabled = true;
usr.UserRoles.Add(userRole as Roles);
entities.User.AddObject(usr);
int result = entities.SaveChanges();
LblMsg.Text = result == 2 ? "User created succesfully." : "An error occured ,please try later.";
entities.Dispose();

Resources