LINQ TO SQL: Detect existing data - c#

I need LINQ code to be able to detect if an entry is input but the datum already exists in the table.
public Boolean CheckAssessment(String assessmentName)
{
{
SQL_TA_SCOREBOARDEntities1 d = new SQL_TA_SCOREBOARDEntities1();
Assessment A_List = new Assessment();
{
var qry2 = from b in contxt.View_Assessment
where b.AssessmentName == assessmentName
select b;
if (qry2 = assessmentName.ToString())
{
return true;
}
else
{
return false;
}
}
}
}
Where assessmentName is the value of the textbox in the a separate C# class.
Boolean i;
i = TAClass.CheckAssessment(txtAssessmentName.ToString());
if (i == true)
{
Label2.Text = "Assessment name already exists.";
}

The correct way is to use Any() extension method. Any() will generate optimized query and will return true as soon as the query found the record.
http://msdn.microsoft.com/en-us/library/bb534338.aspx
So, in your CheckAssessment method, you can do like this:
return (from b in assessments
where b.AssessmentName == assessmentName
select b).Any();

Use the Count() extension to check if there are any matching records:
public bool CheckAssessment(string assessmentName)
{
return (from b in contxt.View_Assessment
where b.AssessmentName == assessmentName
select b).Count() > 0;
}
UPDATE: just for your knowledge, your code could work this way:
public Boolean CheckAssessment(String assessmentName)
{
{
SQL_TA_SCOREBOARDEntities1 d = new SQL_TA_SCOREBOARDEntities1();
Assessment A_List = new Assessment();
{
var qry2 = (from b in contxt.View_Assessment
where b.AssessmentName == assessmentName
select b.AssessmentName).FirstOrDefault();
if (qry2 = assessmentName.ToString())
{
return true;
}
else
{
return false;
}
}
}
}
Just one more comment, always that you have something like:
if (a) { return true; } else {return false;}
you can replace by
return a;

Related

Resharper Search with pattern method call

I want to replace this part of code using "Search with pattern...":
public bool IsDbObjectsOK()
{
var result = 0;
result = usp_IsDbObjectsOK();
if (result == 0)
return true;
return false;
}
public bool UnlockWindow()
{
var result = 0;
result = usp_UnlockWindow();
if (result == 0)
return true;
return false;
}
Replace with:
public bool IsDbObjectsOK()
{
return usp_IsDbObjectsOK() == 0;
}
public bool UnlockWindow()
{
return usp_UnlockWindow() == 0;
}
I tried to use
var $result$ = 0;
$result$ = $usp_IsDbObjectsOK$();
if ($result$ == 0)
return true;
return false;
This doesn't work, because the method call isn't found in any of the code that needs to be replaced.
How to do this?
You need to make sure that you use the correct placeholder type when you set up the search.
Here, result should be an Identifier Placeholder and usp_IsDbObjectsOK should be an Expression Placeholder. When I do that, the replace works as you'd expect.

linq-to-entity dynamic queries

I'am currently migrating our old system to .Net and I encountered this problem.
I want to return the result but I still need to refine it after the function, but using this code, I don't have a choice but to call the result from the database and filter an in-memory result instead which is poor performance.
public IQueryable<User> GetUser(string[] accessCodes)
{
string condition = "";
if (accessCodes == null)
{
condition = " AccessCode IS NOT NULL "
}
else
{
for (int i = 0; i <= accessCodes.Length - 1; i++)
{
condition += " AccessCode LIKE '%" + accessCodes[i].ToString() + "%' ";
if (i + 1 <= code.Length - 1)
{
condition += " OR ";
}
}
}
return context.ExecuteQuery<User>("SELECT * FROM User WHERE " + condition, null).ToList();
}
I've tried this approach this but i'm stuck:
public IQueryable<User> GetUser(string[] accessCodes)
{
IQueryable<User> basequery = from u in context.User
select u;
if (accessCodes == null)
{
basequery = basequery.Where(n => n.AccessCode != null);
}
else
{
for (int i = 0; i <= accessCodes.Length - 1; i++)
{
// what am I supposed to do here?
}
}
return basequery;
}
I'm hoping that there are solutions which do not require third party libraries.
You can try with Any:
else
{
output = output.Where(u => accessCodes.Any(a => u.AccessCode.Contains(a)));
}
or you can use PredicateBuilder:
if (accessCodes == null)
{
output = output.Where(u => u.AccessCode == null);
}
else
{
var predicate = PredicateBuilder.False<User>();
for (int i = 0; i <= accessCodes.Length - 1; i++)
{
predicate = predicate.Or(u => u.AccessCode.Contains(accessCodes[i]))
}
output = output.Where(predicate);
}
I also changed your if part: Where method does not modify source, it returns new query definition, so you have to assign it back to output to make it work.
This should work for you:
IQueryable<User> basequery = from u in context.User
select u;
if (accessCodes == null)
{
basequery = basequery.Where(u => u.AccessCode != null);
}
else
{
basequery = basequery.Where(u => accessCodes.Contains(u=>u.AccessCode));
}
also make sure you return basequery, since output in your method is not defined and not used.

Using Params in function like this C# is it a good practice

FUNCTION **
private void GetComboxItems(params int[] type)
{
try
{
/* DEPARTMENT CODE */
if (type[0] == 1)
{
cmbDept.Items.Clear();
using (SFCDataContext SFC = new SFCDataContext())
{
var Dept = (from i in SFC.Systems_SettingsDepartments
orderby i.Department_ID
select i);
foreach (var q in Dept)
{
cmbDept.Items.Add(q.Department_ID);
}
SFC.Connection.Close();
}
}
/* CORRECTIVE ACTION RECORD CODE */
if (type[1] == 1)
{
cmbCARNo.Items.Clear();
using (SFCDataContext SFC = new SFCDataContext())
{
var CarNo = (from i in SFC.Systems_CARLogSheets
orderby i.CARDocNo
where i.PostStatus == 0
select new
{
Code = i.CARDocNo
});
foreach (var w in CarNo)
{
cmbCARNo.Items.Add(w.Code);
}
SFC.Connection.Close();
}
}
/* MEASUREMENT CODE */
if (type[2] == 1)
{
cmbMeas.Items.Clear();
using (SFCDataContext SFC = new SFCDataContext())
{
var Measure = (from i in SFC.Systems_SettingsMeasurements
orderby i.Measurement_ID
where i.CategoryType == "Measurement"
select new
{
DESC = i.Measurement
});
foreach (var e in Measure)
{
cmbMeas.Items.Add(e.DESC);
}
SFC.Connection.Close();
}
}
/* SUB-MEASUREMENT CODE */
if (type[3] == 1)
{
cmbSubMeas.Items.Clear();
using (SFCDataContext SFC = new SFCDataContext())
{
var SubMeas = (from i in SFC.Systems_SettingsMeasurements
orderby i.Measurement_ID
where i.CategoryType == "Sub-Measurement"
select new
{
DESC = i.Measurement
});
foreach (var r in SubMeas)
{
cmbSubMeas.Items.Add(r.DESC);
}
SFC.Connection.Close();
}
}
}
catch (Exception ex)
{ MessageBox.Show(ex.Message.ToString()); }
}
* FORM LOAD **
private void frmSQMProductivityReports_Load(object sender, EventArgs e)
{
GetComboxItems(1, 0, 1, 0);
}
why is it that at this code.. my 1st if statement is "True" so it does what follows the code inside the if statement and it does. now the 2nd if statement is "False" which it skips the function inside it. but then now the 3rd if statement is "True" which is it should have do same as the 1st but as i have checked couple times it skips the function inside the if statement why is it? is there something wrong in my codes i tried looking at it its seems ok to me..
According to your input, the if conditions that meets the criteria are the first and the third.. note that some statements can be "skipped" if an exception is throw, so placing breakpoints there or printing logs may help you understand better what is happening.
Side notes:
The use of params seems to be redundant in this case (it's mostly used when an unknown #arguments should be passed) since the number of arguments is fixed.
use bool type rather then int for flags

C# error - "Not all code paths return a value"

This is fairly simple method. I use entity framework to get some data and then check some values in a if statement. However right now the method is marked with red.
This is my method:
private bool IsSoleInProduction(long? shoeLastID)
{
if (shoeLastID == null)
{
MessageBox.Show(Resources.ERROR_SAVE,
"Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return false;
}
ISoleService soleService =
UnityDependencyResolver.Instance.GetService<ISoleService>();
List<Sole> entity =
soleService.All().Where(s => s.ShoeLastID == shoeLastID).ToList();
if (entity.Count() != 0)
{
foreach (var items in entity)
{
if (items.Status == 20)
{
return true;
}
else
{
return false;
}
}
}
else
{
return false;
}
}
What am I missing?
You need to take advantage of LINQ with Any, replace your code:
if (entity.Count() != 0)
{
foreach (var items in entity)
{
if (items.Status == 20)
{
return true;
}
else
{
return false;
}
}
}
else
{
return false;
}
with simpler code:
return entity.Any(item => item.Status == 20);
Or even better performance:
return soleService.All()
.Any(s => s.ShoeLastID == shoeLastID
&& s.Status == 20);
Edit: With you comment, below code is what you need:
List<Sole> entity = soleService.All()
.FirstOrDefault(s => s.ShoeLastID == shoeLastID);
return entity == null ? false : entity.Status == 20;
If there's no item in your entity collection, then neither of the containing if/else branches will be executed. In this case there's no return statement anymore, because the else part won't be executed, and outside your foreach you have no return statement.
The compiler does not "see" that if
entity.Count() != 0
then your loop
foreach (var items in entity)
will run at least once. Therefore it sees a possibility of running the forech zero times, and not running the else block.
Suppose first time the entity is enumerated, it yields some (finite number of) items. Then the Count will be non-zero. Then suppose next time the same entity is enumerated then it yields no items! That would cause your code to "fall through" without returning.
It is very probably that you can guarantee that the source yields the same number of items each time it is re-enumerated. But the compiler cannot.
Solution: Just skip if (entity.Count() != 0) and do foreach right away.
You haven't retrun anything from this code block
if (entity.Count() != 0)
{
foreach (var items in entity)
{
if (items.Status == 20)
{
return true;
}
else
{
return false;
}
}
// return someting
}
You might consider doing the following. This will adhere to the "single exit-point" principle (which can sometimes help improve code clarity), and ensure you have a default value in any case:
private bool IsSoleInProduction(long? shoeLastID)
{
// The main change: A default value, assuming "no":
var isSoleInProduction = false;
if (shoeLastID == null)
{
MessageBox.Show(Resources.ERROR_SAVE,
"Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
isSoleInProduction = false;
}
ISoleService soleService =
UnityDependencyResolver.Instance.GetService<ISoleService>();
List<Sole> entity =
soleService.All().Where(s => s.ShoeLastID == shoeLastID).ToList();
if (entity.Count() != 0)
{
foreach (var items in entity)
{
if (items.Status == 20)
{
isSoleInProduction = true;
}
else
{
isSoleInProduction = false;
}
}
}
else
{
isSoleInProduction = false;
}
return isSoleInProduction;
}
What will be your entity.Count() is not 0 and your entity doesn't have any items?
That means your if block will work but foreach part will not work. Since your if part doesn't have any return statement, that's why you get an error.
You should put return statement in your if part.
if (entity.Count() != 0)
{
foreach (var items in entity)
{
if (items.Status == 20)
{
return true;
}
else
{
return false;
}
}
//return true or false
}
If your entity collection has no elements you will not reach a return statement - you need to add a return false forexample as last statement
As the error states there can be cases in which none of your return clause is evaluated (e.g. if there are no elements in your list).
To quickly solve it you can put a default return statement, for example by moving the last return clause outside the else statement. But it really depends on the behavior you'd expect.
private bool IsSoleInProduction(long? shoeLastID)
{
if (shoeLastID == null)
{
MessageBox.Show(Resources.ERROR_SAVE, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
ISoleService soleService = UnityDependencyResolver.Instance.GetService<ISoleService>();
List<Sole> entity = soleService.All().Where(s => s.ShoeLastID == shoeLastID).ToList();
if (entity.Count() != 0)
{
foreach (var items in entity)
{
if (items.Status == 20)
{
return true;
}
else
{
return false;
}
}
}
return false;
}
The compiler can't guarantee that the first call to Count means that the foreach will loop at least once (with good reason, because you could, if you wished, create a collection where this wasn't true). You can do this instead (with no need for the outer if):
foreach (var items in entity)
{
if (items.Status == 20)
{
return true;
}
else
{
return false;
}
}
return false;

Generics and IList related

i have this code below -- a generic method which takes List as one of the input parameters. within the method, is an IF/ELSEIF statement, which runs into a common LINQ call.
Please help me out, so that the LINQ, call could be common to all the IF/ELSEIF's.
private Boolean filterList<T>(List<T> anyOutdoorSports, int numberOfPartcipants)
{
if (anyOutdoorSports == null){ return false ;}
Boolean _returnValue = false;
if (anyOutdoorSports.GetType() == typeof(List<Swimming>))
{
List<Swimming> Swimming = anyOutdoorSports.Cast<Swimming>().ToList();
if (Swimming.Count > 0)
{
int listCount = (from rca in Swimming
where (rca.RecordFields[numberOfPartcipants].ToString()).StartsWith("stamina")
select rca).Count();
_returnValue = listCount > 0 ? true : false;
}
}
else if (anyOutdoorSports.GetType() == typeof(List<Tennis>))
{
List<Tennis> Tennis = anyOutdoorSports.Cast<Tennis>().ToList();
if (Tennis.Count > 0)
{
int listCount = (from rca in Tennis
where (rca.RecordFields[numberOfPartcipants].ToString()).StartsWith("stamina")
select rca).Count();
_returnValue = listCount > 0 ? true : false;
}
}
else if (anyOutdoorSports.GetType() == typeof(List<Soccer>))
{
List<Soccer> Soccer = anyOutdoorSports.Cast<Soccer>().ToList();
if (Soccer.Count > 0)
{
int listCount = (from rca in Soccer
where (rca.RecordFields[numberOfPartcipants].ToString()).StartsWith("stamina")
select rca).Count();
_returnValue = listCount > 0 ? true : false;
}
}
return _returnValue;
}
THANKS TO ALL WHO VIEWED AND HELPED.
This is straightforward if there is a common base class for Tennis, Soccer and Swimming with a RecordFields property:
private boolean FilterList<T>(IEnumerable<T> anyOutdoorSports, int numberOfParticipants) where T : OutdoorSport
{
if(anyOutdoorSports == null) return false;
return anyOutdoorSports.Any(s => s.RecordFields[numberOfParticipants].ToString().StartsWith("stamina"));
}
Since all of your types seem to have an RecordFields property you could add an Interface and use that instead of the Generic.
Other than that you'd have to resort to Func<> expressions.
Assuming that all the classes inherit from the same base class, which contains RecordFields, you can create a generic constraint on the method and remove the ifs entirely.
private Boolean filterList<T>(List<T> anyOutdoorSports, int numberOfPartcipants)
where T : OutdoorSport
{
if (anyOutdoorSports == null){ return false ;}
Boolean _returnValue = false;
if (anyOutdoorSports.Count > 0)
{
int listCount = (from rca in anyOutdoorSports
where (rca.RecordFields[numberOfPartcipants].ToString()).StartsWith("stamina")
select rca).Count();
_returnValue = listCount > 0;
}
return _returnValue;
}

Categories

Resources