Linq to Sql problem - c#

I have 2 tables Users and Queries. They are connected via FK(UserId) in Queries table.
I need to add queries added, for example, by user with login "Bob" to all users.
Here is a chunk of code i'm using:
public bool SaveUserQuery(string userName, Query query) {
var db = new UserDataClassesDataContext();
Table<User> users = db.Users;
if ( userName.ToLower() == "bob" ) {
foreach ( var user in users ) {
var tempQuery = new Query();
tempQuery.Name = query.Name;
tempQuery.FolderName = query.FolderName;
tempQuery.Layout = query.Layout;
tempQuery.Description = query.Description;
tempQuery.Query1 = query.Query1;
tempQuery.UserID = user.UserId;
try {
user.Queries.Add(q);
}
catch (Exception e) {
Logger.Log.Error("attach", e);
}
}
db.SubmitChanges();
return true;
}
}
It throws error when adding:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Queries_Users". The conflict occurred in database "OLAPUsers", table "dbo.Users", column 'UserId'.
How can i fix this or archive the goal i have?

Make sure that your primary keys are setup correctly in the DB schema. You can query tables without primary keys, but you can't do inserts unless everything is setup correctly, and the data context's view of the DB is current.

Try this:
public bool SaveUserQuery(string userName, Query query)
{
var db = new DataContext();
if ( userName.ToLower() == "bob" )
{
List<Query> queries = new List<Query>();
foreach ( var user in db.GetTable<Users>())
{
Query tempQuery = new Query(query.Name, query.FolderName, query.Layout, query.Description, query.Query1, user.UserId);
//and ofc create this constructor
queries.Add(tempQuery);
}
db.GetTable<Query>().InsertAllOnSubmit(queries);
db.SubmitChanges();
return true;
}
}

Related

Attach Entity with parameter value null using Entity Framework

So, I'm trying to update rows where LOGIN IS NULL and ID = 1. If there are no rows with these parameters then add new row. I use attach to make that in 1-2 queries so I'm trying to avoid SELECT first and then update.
Problem in NULL value. EF simply ignores LOGIN since it has null value, however I need to find only rows where LOGIN IS NULL. Can I solve that problem without additional SELECT query?
My code:
using (var db = new EntityContext())
{
var ent = new Entity { ID = 1, LOGIN = null };
db.Entities.Attach(ent);
ent.LOGIN = "Whatever";
ent.EMAIL = "Whatever";
int count = db.SaveChanges();
if (count == 0)
{
var clone_ent = new Entity { LOGIN = "Whatever", PASS = "Whatever" };
db.Entities.Add(clone_ent);
db.SaveChanges();
}
}
SQL analog:
UPDATE Entities SET LOGIN = #LOGIN, EMAIL = #EMAIL
WHERE ID = 1 AND LOGIN IS NULL
IF ##ROWCOUNT = 0
INSERT INTO Entities (LOGIN, EMAIL)
VALUES #LOGIN, #EMAIL
Unfortunately, it is not possible to include a WHERE condition into UPDATE statements in entity framework so you will have to select, then update or insert, e.g.:
using (var db = new EntityContext())
{
var ent = db.Entities.Where(x => x.ID == 1 && x.LOGIN == null).FirstOrDefault();
if (ent != null)
{
ent.LOGIN = "Whatever";
ent.EMAIL = "Whatever";
}
else
{
db.Entities.Add(ent);
}
db.SaveChanges();
}

how to insert data into one-to-many relationship using linq to sql

how to insert data into one-to-many relationship using linq to sql. i have two table first is person and secondly is order ,i have make a relationship between both table,i want to insert data into both table at a time
public ActionResult Add(CustomerViewData data)
{
string message = "";
var item = data.Customer;
try
{
_repositoryCustomer.Insert(item);
_repositoryCustomer.Save();
return RedirectToAction("Edit", new { message = Constants.RecordSaved, id = item.CustomerId});
}
catch (Exception ex)
{
message = "Customer had error saving.";
Log.Error(message, ex);
}
return View("Edit", new CustomerViewData { PageMode = PageMode.Add, Message = message });
}
using (MyDataContext dc = new MyDataContext())
{
Person p = new Person();
Order o = new Order();
p.Orders.Add(o); //connect the objects into an object graph.
dc.Persons.Add(p); //add the graph to the data context
dc.SubmitChanges(); //save it all.
}

Get the insert and update SQL queries from LINQ To Sql data context

I have a LINQ To Sql data context, with a mapping to tables User and Group. A user belongs to a Group.
So I would like to get the corresponding SQL generated for Insert/Update by data context against a particular entity.
For e.g.
using (var context = new TestBedDataContext())
{
using (var trans = new TransactionScope())
{
context.Users.InsertOnSubmit(new User
{
Name = "Test",
Password = "Password",
Username = "test",
Group1 = new Group
{
Name = "Group1"
}
});
// Get the query for User entity
}
}
Here I would like to get the queries that will be generated for inserting a new user along with Group entity.
I know context.Log property can be used to capture the entire SQL generated, the problem with that approach is, it will catch all the SQL which are not in my interests (like change scripts for some other entities)
public void addPatientInformation() {
using(DbClassesDataContext myDb = new DbClassesDataContext()) {
myDb.PatientInfos.InsertOnSubmit(new PatientInfo {
Phy_ID = physcianID,
Pat_First_Name = txtFirstName.Text,
Pat_Middle_Init = txtMiddleName.Text,
Pat_Last_Name = txtLastName.Text,
Pat_Gender = cmbGender.Text,
Pat_Marital_Status = cmbMaritalStatus.Text,
Pat_Date_Of_Birth = dtpDOB.Value,
Pat_Home_Add = txtHomeAdd.Text,
Pat_Home_Num = txtPhone.Text,
Pat_Work_Add = txtWorkAdd.Text,
Pat_Work_Num = txtWorkPhone.Text,
Pat_Prim_Physician = txtPrimPhysician.Text,
Pat_Ref_Physician = txtRefePhysician.Text,
});
myDb.SubmitChanges();
}
}

Insert and update multi item into database in the same time

I have an empty data base.
I want to add multi records into data base.
while inserting record to data base i want to check if my product inserted in same date donot add it again(i want to change some it's filed and update it's content).
i used this code but it just add some data into data base (it can't check for existing product.)
var AllData = ClsDataBase.Database.InsertProductTbls;
foreach(item in AllData)
{
//Update
if (Exist(datefa))
{
var query = ClsDataBase.Database.CustomerProductTbls.SingleOrDefault
(data => data.CustomerId == AllData .CustomerId );
int? LastProductTotal = query.CustomerProducTtotal;
query.CustomerProducTtotal = LastProductTotal + ClsInsertProduct._InsertProductNumber;
}
//Insert
else
{
_CustomerProductTbl = new CustomerProductTbl();
_CustomerProductTbl.CustomerId = AllData ._CustomerId;
_CustomerProductTbl.CustomerProductDateFa = AllData.datefa
.
.
.
ClsDataBase.Database.AddToCustomerProductTbls(_CustomerProductTbl);
}
}
}
ClsDataBase.Database.SaveChanges();
if i use ClsDataBase.Database.SaveChanges(); for both update and insert part i will return this error:
An error occurred while starting a transaction on the provider connection. See the inner exception for details.
please help.
I got the solution by opening database conection for each repeat loop:
foreach(item in AllData)
{
using (StorageEntities context = new StorageEntities())
{
//Update
if (Exist(datefa))
{
var query = ClsDataBase.Database.CustomerProductTbls.SingleOrDefault
(data => data.CustomerId == AllData .CustomerId );
int? LastProductTotal = query.CustomerProducTtotal;
query.CustomerProducTtotal = LastProductTotal + ClsInsertProduct._InsertProductNumber;
}
//Insert
else
{
_CustomerProductTbl = new CustomerProductTbl();
_CustomerProductTbl.CustomerId = AllData ._CustomerId;
_CustomerProductTbl.CustomerProductDateFa = AllData.datefa;
ClsDataBase.Database.AddToCustomerProductTbls(_CustomerProductTbl);
}
ClsDataBase.Database.SaveChanges();
}
}

Adding data in Entity Framework in tables with Foreign Key

I am struggling to Insert data in a table with Foreign key relationship.I did read a
few articles on how to do this but did not help much and decided to open up a new question.
Scenario :
User table has a foreign key on role table ID.
On the role table Id is integer and is auto incremented
Here is my code,
SalesTrainerEntities db = new SalesTrainerEntities();
var user = new User();
var role = db.Role.FirstOrDefault(r => r.ID == 1);
user.UserName = "test";
user.Pass = "123";
user.CreatedBy = "test";
user.DtCreated = DateTime.Now;
user.Role = role;
//user.RoleId = 1;
//user.EntityKey = new EntityKey("Role", "ID", 1);
//user.RoleReference.EntityKey = new EntityKey("Role", "ID", 1);
db.AddToUser(user);
db.SaveChanges();
On Save Changes I get error stating
Unable to update the EntitySet 'User' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.
Any pointers will be highly appreciated.
Regards,
Sab
I used to add children entities this way, I'm assuming a relation 1:N between user and role.
using (Entities db = new Entities())
{
var user = new User();
// fill user data..
var newRole = db.Role.FirstOrDefault(r => r.ID == 1);
if(newRole!=null)
{
user.roles.AddObject(newRole);
db.users.AddObject(user);
db.SaveChanges();
}
}
//Edit - Updating db
using (Entities db = new Entities())
{
var existingUser = db.User.FirstOrDefault(r => r.ID == 100);
if(existingUser !=null)
{
existingUser.Name = "New name";
db.SaveChanges();
}
}

Categories

Resources