Delete from 2 SQL tables with SilverLight Linq-to-SQL - c#

I got 2 tables in SQL that both have a field called Selection_ID. I want to delete all rows with Selection_ID = inpSelectionID using the Linq-to-SQL.
My tables:
My C# function:
void buttonDeleteSelectionList_Click(object sender, RoutedEventArgs e, Canvas canvasAdvancedSearchFieldResults, int inpSelectionID)
{
PositionServiceReference.PositionServiceClient service = new PositionServiceReference.PositionServiceClient();
service.DeleteSelectionCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(service_DeleteSelectionCompleted);
service.DeleteSelectionAsync(inpSelectionID);
}
My Service Code PositionService.svc.cs:
[OperationContract]
void DeleteSelection(int inpSelectionID)
{
PositionDataClassesDataContext context = new PositionDataClassesDataContext();
context.Lloyds_Selection.DeleteOnSubmit(inpSelectionID);
context.SubmitChanges();
context.Lloyds_Selection_Vessels.DeleteOnSubmit(inpSelectionID);
context.SubmitChanges();
}

DeleteOnSubmit requires the entity object as a parameter, so you can't delete item without selecting it from database first. There is DeleteAllOnSubmit method too, but it requires IEnumerable of entities as well. You can use it like that:
context.Lloyds_Selection.DeleteAllOnSubmit(context.Lloyds_Selection.Where(l => l.Selection_ID == inpSelectionID));
However, you can use DataContext.ExecuteCommand to execute raw SQL against your database:
string command = string.format("DELETE FROM Lloyds_Section WHERE Selection_ID = {0}", inpSelectionID");
context.ExecuteCommand(command );

Related

How to filter "table_2" depending on the selected entry in "table_1"?

I'm using:
Entity Framework v6.2.0
SQL Server 2012
I have these tables:
tbl_01_Groups;
tbl_02_Students;
tbl_03_GroupsStud;
 
The tbl_01_Groups table is displayed in dataGridView1. One student can be in several groups.
To solve this problem, I suspect that it is necessary to build the table of relations tbl_03_GroupsStud.
Question: how to make dataGridView2 display table_2 records that belong to the group selected in dataGridView1?
Requirements for table_2:
table_2 should contain the following fields:
[tbl_02_Students].[NameStud];
[tbl_02_Students].[Property_1];
[tbl_01_Groups].[nameGroup];
... other columns as needed
if changes are made in the table_2 record, then these changes are displayed in the original source;
if an entry is added to the table_2, then this entry is displayed in the source;
Table_2 is planned to be used in another query.
How to make the table_2 meet the above requirements?
My code:
ContextDB cntxtDB;
public Frm1UC()
{
InitializeComponent();
cntxtDB = new ContextDB();
}
private void Frm1UC_Load(object sender, EventArgs e)
{
Fill_dataGridView1();
}
public void Fill_dataGridView1()
{
try
{
cntxtDB.tbl_01_Groups.Load();
bs_Grid1.DataSource = cntxtDB.tbl_01_Groups.Local.ToBindingList();
dataGridView1.DataSource = bs_Grid1;
}
catch (Exception ex)
{
string s = ex.Message;
string t = ex.StackTrace;
// throw;
MessageBox.Show(s);
}
}
tbl_01_Groups:
tbl_02_Students:
tbl_03_GroupsStud:
dataGridView1, dataGridView2:
Update_1
Something like I managed to do with the help of queries in MSAccess:
Request req_GroupsStud_Stud:
SELECT tbl_03_GroupsStud.*, tbl_02_Students.NameStud
FROM tbl_03_GroupsStud
INNER JOIN tbl_02_Students
ON tbl_03_GroupsStud.id_stud = tbl_02_Students.id_stud;
Request req_GroupsStud_CurGroup:
SELECT req_GroupsStud_Stud.*, req_GroupsStud_Stud.id_group
FROM req_GroupsStud_Stud
WHERE (((req_GroupsStud_Stud.id_group)=[Forms]![frm_00_00_MainForm]![id_group_Frm]));
From the form, using the expression [Forms]![Frm_00_00_MainForm]![Id_group_Frm], the parameter [id_group_Frm] is passed to the request.
I don’t understand how to do the same thing using the entity-framework and MS SQL Serever.

How to delete table on Cassandra using C# Datastax driver?

var keyspace = "mydb";
var datacentersReplicationFactors = new Dictionary<string, int>(0);
var replication = ReplicationStrategies.CreateNetworkTopologyStrategyReplicationProperty(datacentersReplicationFactors);
using (var cluster = Cluster.Builder().AddContactPoints("my_ip").Build())
using (var session = cluster.Connect())
{
session.CreateKeyspaceIfNotExists(keyspace, replication, true);
session.ChangeKeyspace(keyspace);
var entityTable = new Table<Models.Entity>(session);
var attributeTable = new Table<Models.Attribute>(session);
entityTable.CreateIfNotExists(); // Worked
attributeTable.CreateIfNotExists(); // Worked
entityTable.Delete(); // Does nothing
attributeTable.Delete(); // Does nothing
}
EDIT: Without using raw queries session.Execute("DROP TABLE entities;"); working fine.
Delete() method is not intended for drop of the tables. It returns representation of a DELETE cql statement. If you call it, you just get {DELETE FROM entities}.
If you need to drop a table, the easiest way is just to execute DROP statement:
session.Execute("DROP TABLE entities;");
Unless there is already a method for dropping tables that I not aware of, you can use this extensions.
public static class DastaxTableExtensions
{
public static void Drop<T>(this Table<T> table)
{
table.GetSession().Execute($"DROP TABLE {table.Name};");
}
public static void DropIfExists<T>(this Table<T> table)
{
table.GetSession().Execute($"DROP TABLE IF EXISTS {table.Name};");
}
}
Then you can use it like this
entityTable.Drop();
attributeTable.DropIfExists();

Calling a parameterized stored procedure using WCF and LINQ to SQL

How can I call a parameterized stored procedure usp_Get_Products from my WCF service? I have tried calling it without any parameters it works fine but I don't know how to pass a textbox value as a parameter from my About.xaml.cs file.
Service.svc.cs file
public List<Product> GetProducts()
{
ProductDataClassDataContext db = new ProductDataClassDataContext();
var products = db.usp_Get_Products();
return products.ToList();
}
Views/About.xaml.cs file
private void OnSearchProductClick(object sender, RoutedEventArgs e)
{
ServiceReference1.Service1Client webService = new ServiceReference1.Service1Client();
webService.GetProductsCompleted += new EventHandler<GetProductsCompletedEventArgs>(webService_GetProductsCompleted);
webService.GetProductsAsync();
txtblcName.Text = txtName.Text; //Send this as parameter to usp_Get_Products
}
public void webService_GetProductsCompleted(object sender, ServiceReference1.GetProductsCompletedEventArgs e)
{
ProductGrid.ItemsSource = e.Result; //Binding Datagrid
}
How can I send txtName.Text from my xaml.cs file as parameter when calling the stored procedure? I know I'm missing some concepts, I'm new to WCF plus I have never worked on silverlight..
Are you sure the stored procedure accepts parameters?
Also can you please post your ProductDataClassDataContext.
Ideally you should modify your service contract to accept the parameters,
in case you don't wanna do it
you can do a filter on the products list like
var products = await webService.GetProductsAsync();
var filteredProduct = products.Where(item=> item.Name == txtName.Text);

LinqPad connect two azure databases on same server

Per the FAQ (1), I can add additional databases to my existing connection in a number of ways. I have tried them all, and none work for SQL Azure.
In fact, SQL Azure as a provider, doesn't even include the option to "Include additional databases."
Can someone please tell me a workaround for LinqPad to connect two databases? I am trying to create a migration linqpad script to sync data from one database to another.
http://www.linqpad.net/FAQ.aspx#cross-database
This fails because SQL Azure does not let you create linked servers. See
Can linked server providers be installed on a SQL Azure Database instance?
If you simply want to copy data from one database to another, and the schemas are the same, a workaround is to create a separate connection using the same TypedDataContext class:
void Main()
{
CopyFrom<Customer>("<source connection string>");
}
void CopyFrom<TTable> (string sourceCxString) where TTable : class
{
// Create another typed data context for the source. Note that it must have compatible schema:
using (var sourceContext = new TypedDataContext (sourceCxString) { ObjectTrackingEnabled = false })
{
// Delete the rows currently in our table:
ExecuteCommand ("delete " + Mapping.GetTable (typeof (TTable)).TableName);
// Insert the rows from the source table into the target table and submit changes:
GetTable<TTable>().InsertAllOnSubmit (sourceContext.GetTable<TTable>());
SubmitChanges();
}
}
Simple Select Example:
void Main()
{
SimpleSelect("<your conn string>");
}
void SimpleSelect (string sourceCxString)
{
// Create another typed data context for the source. Note that it must have compatible schema:
using (var sourceContext = new TypedDataContext (sourceCxString) { ObjectTrackingEnabled = false })
{
sourceContext.Assignee.OrderByDescending(a => a.CreateTimeStamp).Take(10).Dump();
Assignee.OrderByDescending(a => a.CreateTimeStamp).Take(10).Dump();
}
}

Linq Include method not showing up in viewmodel

I have a Silverlight app using mvvm with ria services. I have a textbox on the view that the user puts in a Job Number and clicks find. This find button is using the ICommand in xaml to go here..
public ICommand FindJob
{
get
{
return new DelegateCommand(BeginFindJob, (o) => true);
}
}
public void BeginFindJob(object o)
{
if (!IsDesignTime)
{
IsLoading = true;
string jobnum = o.ToString();
OnPropertyChanged("IsLoading");
LoadOperation<Job> loadOp = _context.Load<Job>(_context.GetJobsByJobNumQuery(jobnum));
loadOp.Completed += new EventHandler(loadOp_Completed);
}
}
It uses the GetJobsByJobNumQuery in my ria service like so..
public IQueryable<Job> GetJobsByJobNum(string JobNum)
{
var query = ((from j in this.ObjectContext.Jobs
where j.JobNumber == JobNum
select j) as ObjectQuery<Job>).Include("JobHeadings").Include("JobContracts").Include("JobTags").Include("JobMarket");
return query;
}
Im wanting it to return all the information about the job, so i wrote the query above to include all those relationships. Putting a breakpoint on the linq query and looking at the results, it has exactly what I wont. All the fields, JobHeadings and Contracts are working and bringing back all the bindings to that job. So now I bring that query back in my viewmodel and populate the fields, like so..
void loadOp_Completed(object sender, EventArgs e)
{
try
{
LoadOperation<Job> loadOp = sender as LoadOperation<Job>;
if (!loadOp.HasError)
{
_job = loadOp.Entities.FirstOrDefault<Job>();
base.IsLoading = false;
base.ProgressBarVisibility = Visibility.Collapsed;
base.OnPropertyChanged("IsLoading");
base.OnPropertyChanged("ProgressBarVisibility");
base.OnPropertyChanged("CurrentJob");
}
}
catch (Exception ex)
{
}
}
My problem is, that no relationship data is coming back. All the basic Job info is coming back from the Job table in my db, but none of the info from the related tables is coming back in my viewmodel. Putting a bp in and looking at _job, which should contain everything, all the relationship tables JobHeading/JobContract say 'Enumeration yielded no results.'
So how is it not making its way back through to the viewmodel? What can i do to get the full query results put into the view/viewmodel so I can make changes?
Should the Includes not be higher up on the ObjectSet? like this:
public IQueryable<Job> GetJobsByJobNum(string JobNum)
{
var query = ((from j in this.ObjectContext.Jobs.Include("JobHeadings").Include("JobContracts").Include("JobTags").Include("JobMarket")
where j.JobNumber == JobNum
select j) as ObjectQuery<Job>);
return query;
}
This was a problem with the metadata service not picking up my latest table associations. After i went through that mess of regenerating the metadata, it was a simple matter of including and associating the correct keys. Thank you Quinton Bernhardt for your effort!

Categories

Resources