How to control quantity and increase - c#

I'm using webservice to add product to basket here the code ;
[WebMethod]
public void calistir(int urunid, string GirenIp)
{
using (Models.DermabonEntities db = new Models.DermabonEntities())
{
var productName = (from i in db.Product
where i.Id == urunid
select i.ProductName).FirstOrDefault();
var productPrice = (from i in db.Product
where i.Id == urunid
select i.ProductPrice).FirstOrDefault();
var productId = (from i in db.Product
where i.Id == urunid
select i.Id).FirstOrDefault();
var productPic = (from i in db.Product
where i.Id == urunid
select i.ProductPicture).FirstOrDefault();
var userIp = GirenIp;
Basket create = new Basket();
create.ProductName = productName;
create.ProductId = productId;
create.ProductPrice = productPrice;
create.ProductPic = productPic;
create.UserId = userIp;
var qua = "2";
create.ProductQuantity = Convert.ToInt32(qua);
db.Basket.Add(create);
db.SaveChanges();
}
}
Here I add quantity of product manually. But I want to control if there is same product increase quantity and if not make quantity 1.
I've tried something like this ;
var CountProduct= db.Basket.FirstOrDefault();
if (CountProduct.ProductId == urunid)
{
CountProduct.ProductQuantity += Convert.ToInt32(adet);
create.ProductQuantity = Convert.ToInt32(adet);
db.SaveChanges();
}
GirenIp = sessionID which comes from ajax , urunId = ProductId which comes from ajax , adet means quantity.
Ajax ;
function sepeteEkle(id) {
var urunid = id;
var GirenIp = $("#userId").val();
$.ajax({
dataType: "json",
type: "POST",
contentType: "application/json",
url: "/Admin/WebService/Control.asmx/calistir",
data: "{'urunid':'" + urunid + "','GirenIp':'" + GirenIp + "' }",
success: function(){
$("#cartContent").load("MiniSepet.aspx #cartContent");
},
error: function () {
$("#cartContent").load("MiniSepet.aspx #cartContent");
}
});
return false;
}
$(document).on('click', '.sepetat', function () {
var nId = $(this).data("id")
sepeteEkle(nId);
});
sepetat= add to basket
basket table ;
public partial class Basket
{
public int Id { get; set; }
public string UserId { get; set; }
public Nullable<int> ProductId { get; set; }
public string ProductName { get; set; }
public Nullable<double> ProductPrice { get; set; }
public Nullable<int> ProductQuantity { get; set; }
public string ProductPic { get; set; }
}
}

You do not want to run multiple LINQ queries on the same object, just to get several properties. That will cause SQL code to be run multiple times (4 times in your example). Just fetch the object once and use its properties.
You also want to clean things up a bit and use a simple pattern like this:
public void calistir(int urunid, string GirenIp)
{
using(Models.DermabonEntities db = new Models.DermabonEntities())
{
// Find the product by primary key
var product = db.Product.Find(urunid);
if (product != null)
{
var productName = product.ProductName;
var productPrice = product.ProductPrice;
var productId = urunid;
var productPic = product.ProductPicture;
var userIp = GirenIp;
// Get existing basket entry if any based on session/user id and product id
Basket basket = dn.basket.FirstOrDefault(x=>x.UserId == userIp && x.ProductId == productId);
if (basket == null)
{
// basket does not already exist, so add new basket
basket = new Basket()
{
// You can use property assignment with constructors
ProductName = productName,
ProductId = productId,
ProductPrice = productPrice,
ProductPic = productPic,
UserId = userIp,
ProductQuantity = 1 // Your initial quantity
}
db.Basket.Add(basket);
}
else
{
// Existing basket, just increase the quantity
basket.ProductQuantity++;
}
db.SaveChanges();
}
}
}
Most of your temporary variables are not actually needed:
public void calistir(int urunid, string GirenIp)
{
using(Models.DermabonEntities db = new Models.DermabonEntities())
{
// Find the product by primary key
var product = db.Product.Find(urunid);
if (product != null)
{
var userIp = GirenIp;
// Get existing basket entry if any based on session/user id and product id
Basket basket = dn.basket.FirstOrDefault(x=>x.UserId == userIp && x.ProductId == urunid);
if (basket == null)
{
// basket does not already exist, so add new basket
basket = new Basket()
{
// You can use property assignment with constructors
ProductName = product.ProductName,
ProductId = product.ProductId,
ProductPrice = product.ProductPrice,
ProductPic = product.ProductPicture,
UserId = userIp,
ProductQuantity = 1 // Your initial quantity
}
db.Basket.Add(basket);
}
else
{
// Existing basket, just increase the quantity
basket.ProductQuantity++;
}
db.SaveChanges();
}
}
}

Related

How to shape return data?

While returning data in Postman, I receive full user information such as password hash and password salt. My idea is to return only his username, so that it looks like "user" : "tom" without his data. I should use automapper ? Or how to set the Dto's to return correct data. Any tips ?
public async Task < ActionResult < ProductDto[] >> AddProduct(string username,
ProductDto productDto)
{
User u = await _context.Users
.Where(x => x.UserName == username)
.Include(x => x.Products)
.SingleOrDefaultAsync();
if (u != null)
{
var product = new Product
{
Name = productDto.Name,
Price = productDto.Price,
UserId = u.Id
};
u.Products.Add(product);
await _context.SaveChangesAsync();
}
return u.Products.ToArray();
}
public class Product : BaseEntity
{
public string Name { get; set; }
public decimal Price { get; set ;}
public User User { get; set; }
public int UserId { get; set; }
}
public class ProductDto
{
public string Name { get; set; }
public string Username { get; set; }
public decimal Price { get; set; }
}
Output in postman: https://i.stack.imgur.com/vNi7J.png
You are returning an array of Product objects, but it seems that what you really want is to return an array of ProductDto objects.
You can use the following code to construct the array of ProductDto objects. Insert it after the if (u != null) check:
if (u != null)
{
var product = new Product
{
Name = productDto.Name,
Price = productDto.Price,
UserId = u.Id
};
u.Products.Add(product);
await _context.SaveChangesAsync();
}
else
{
return new ProductDto[] {};
}
var productDtos = new ProductDto[u.Products.Count];
for (var i = 0; i < u.Products.Count; i++)
{
productDtos[i] = new ProductDto
{
Name = product.Name,
Username = product.User.UserName,
Price = product.Price
};
}
return productDtos;
Alternatively, you can use LINQ:
if (u != null)
{
var product = new Product
{
Name = productDto.Name,
Price = productDto.Price,
UserId = u.Id
};
u.Products.Add(product);
await _context.SaveChangesAsync();
}
else
{
return new ProductDto[] {};
}
var productDtos = u.Products
.Select(p => new ProductDto
{
Name = p.Name,
Username = p.User.UserName,
Price = p.Price
})
.ToArray();
return productDtos;

Fetching data in level 3 of self-referencing / parent-child relationship

I am programming a multilevel menu / submenu in ASP.NET MVC.
I have this table:
Id Name ParentId
----------------------------------
1 Menu1 null
2 Menu2 null
3 Submenu1-menu1 1
4 Submenu2-menu1 1
5 1-Level3-submenu1 3
6 2-Level3-submenu1 3
7 3-Level3-submenu1 3
To fetch the data using Entity Framework, I wrote this code:
var category = _context.Categories
.Include(p => p.SubCategories)
.Where(p => p.ParentId == null)
.ToList()
.Select(p => new MenuItemDto
{
CatId = p.Id,
Name = p.Name,
Child = p.SubCategories.ToList().Select(child => new MenuItemDto
{
CatId = child.Id,
Name = child.Name,
Child = child.SubCategories?.ToList().Select(grandchild => new MenuItemDto
{
CatId = grandchild.Id,
Name = grandchild.Name,
}).ToList()
}).ToList(),
}).ToList();
public class MenuItemDto
{
public long CatId { get; set; }
public string Name { get; set; }
public List<MenuItemDto> Child { get; set; }
}
but the result is that just Menu1 and Menu2 and the children of Menu1 (Submenumen1-menu1 and Submenu2-menu1), I could not fetch 1-Level3-submenu1 and 2-Level3-submenu1 and 3-Level3-submenu1
I would recommend simplifying the database call and building the tree in code as this would be more efficient.
To do this create a recursive method for building the children of an parent.
In the example below I am manually generating the Database list and taking the assumption of the ParentId being a string. I am also manually looping through the output and only going to 3 levels for this example. You should be aware that you can have infinite levels if you self reference.
You can see a working example of the code below at https://dotnetfiddle.net/BCyO6I
public class MenuItemDb
{
public long Id { get; set; }
public string Name { get; set; }
public string ParentId { get; set; }
}
public class MenuItemDto
{
public long CatId { get; set; }
public string Name { get; set; }
public List<MenuItemDto> Children { get; set; }
}
public class Program{
public static void Main(string[] args){
//get all data from Context
//var categories = _context.Categories.ToList();
//for the purpose of this test manually generate categories
List<MenuItemDb> categories = new List<MenuItemDb>();
categories.Add(new MenuItemDb() {
Id = 1, Name = "Menu1", ParentId = null
});
categories.Add(new MenuItemDb() {
Id = 2, Name = "Menu2", ParentId = null
});
categories.Add(new MenuItemDb() {
Id = 3, Name = "Submenu1-menu1", ParentId = "1"
});
categories.Add(new MenuItemDb() {
Id = 4, Name = "Submenu1-menu2", ParentId = "1"
});
categories.Add(new MenuItemDb() {
Id = 5, Name = "1-Level3-submenu1", ParentId = "3"
});
categories.Add(new MenuItemDb() {
Id = 6, Name = "2-Level3-submenu1", ParentId = "3"
});
categories.Add(new MenuItemDb() {
Id = 7, Name = "3-Level3-submenu1", ParentId = "3"
});
List<MenuItemDto> menu = new List<MenuItemDto>();
//build top level
foreach(var child in categories.Where(w => w.ParentId == null))
{
MenuItemDto childDto = new MenuItemDto() {
CatId = child.Id,
Name = child.Name
};
AddChildren(childDto, categories);
menu.Add(childDto);
}
foreach(var item in menu){
Console.WriteLine(item.Name);
foreach(var childLevel1 in item.Children){
Console.WriteLine(" -- " + childLevel1.Name);
foreach(var childLevel2 in item.Children){
Console.WriteLine(" -- " + childLevel2.Name);
}
}
}
}
public static void AddChildren(MenuItemDto parent, List<MenuItemDb> categories){
parent.Children = new List<MenuItemDto>();
foreach(var child in categories.Where(w => w.ParentId == parent.CatId.ToString()))
{
var childDto = new MenuItemDto() {
CatId = child.Id,
Name = child.Name
};
AddChildren(childDto, categories);
parent.Children.Add(childDto);
}
}
}
I think you want to create tree of categories so you can do like that:
first Get all of your category and put it in to the memory for better performance of sorting.
with this you can do it:
var unsortedCategories = _context.Categories.ToList()
and then sort your category with parentId
private async Task<List<Category>> SortCategoriesForTreeAsync(
List<Category> source,
int parentId = 0,
CancellationToken cancellationToken = default)
{
if (source is null)
throw new ArgumentNullException(nameof(source));
var result = new List<Category>();
foreach (var cat in source.Where(c => c.ParentId == parentId).ToList())
{
result.Add(cat);
result.AddRange(await SortCategoriesForTreeAsync(source, cat.Id, true, cancellationToken));
}
if (ignoreCategoriesWithoutExistingParent || result.Count == source.Count)
return result;
//find categories without parent in provided category source and insert them into result
foreach (var cat in source)
if (result.FirstOrDefault(x => x.Id == cat.Id) is null)
result.Add(cat);
return result;
}
use method like this:
var sortedAllCategory = await SortCategoriesForTreeAsync(unsortedCategories)
then when you have sorted categories you can create the tree:
private async Task<List<MenuItemDto>> CreateCategories(List<Category> allSortedCategories, int categoryId, CancellationToken cancellationToken)
{
var categories = allSortedCategories
.Where(c => c.ParentId == categoryId);
var listModels = new List<MenuItemDto>();
foreach (var category in categories)
{
var categoryModel = new MenuItemDto
{
CatId = category.Id,
Name = category.Name,
};
var subCategories = await PrepareCategories(allSortedCategories, category.Id, cancellationToken);
categoryModel.Child.AddRange(subCategories);
categoryModel.HaveSubCategories = categoryModel.SubCategories.Any();
listModels.Add(categoryModel);
}
return listModels;
}
so your can use this method to create tree like this:
var result = await PrepareCategories(sortedAllCategory, 0, cancellationToken);

how to get count Of Product according Store

I have three Table : Product and StoreDetail , Store
Store Table holds storeName .
I want get count of product according storeName , to do this I use belowe code :
var stocksQuery = storeDetails.GroupBy(row => new { row.StoreId, row.ProductId }).AsQueryable();
List<StockStatusViewModel> result = new List<StockStatusViewModel>();
foreach (var item in stocksQuery)
{
result.Add(new StockStatusViewModel
{
Quantity = item.Sum(row => row.Quantity),
ProductCombinationId = item.Key.ProductAttributeCombinationId,
StoreId = item.Key.StoreId,
// here I need productName and StoreName
});
}
but I need to storeName and ProductName , how can I get these ?
here Is my classes:
public class StoreDetail
{
public Product Product{ get; set; }
public Guid ProductId { get; set; }
}
public class Product{
public ICollection<StoreDetail> StoreDetails { get; set; }
}
Can you try some thing like this, instead of group by StoredId and ProductId, I will group by Store and Product
var stocksQuery = storeDetails.GroupBy(row => new { row.Store, row.Product }).AsQueryable();
List<StockStatusViewModel> result = new List<StockStatusViewModel>();
foreach (var item in stocksQuery)
{
result.Add(new StockStatusViewModel
{
Quantity = item.Sum(row => row.Quantity),
ProductCombinationId = item.Key.ProductAttributeCombinationId,
StoreId = item.Key.StoreId,
StoreName = item.Key.Store.StoreName,
ProductName = item.Key.Product.ProductName
});
}
For better performance, I think we just select what we need so we can change the code to
var stocksQuery = storeDetails.GroupBy(row => new { row.StoreId, row.Store.StoreName, row.ProductId, row.Product.ProductName }).AsQueryable();
List<StockStatusViewModel> result = new List<StockStatusViewModel>();
foreach (var item in stocksQuery)
{
result.Add(new StockStatusViewModel
{
Quantity = item.Sum(row => row.Quantity),
ProductCombinationId = item.Key.ProductAttributeCombinationId,
StoreId = item.Key.StoreId,
StoreName = item.Key.StoreName,
ProductName = item.Key.ProductName
});
}

Conditional Joins With Linq

Is there a way to progressively / conditionally add joins to a query? I am creating a custom reporting tool for a client, and the client is given a list of objects he/she can select to query on. There will always be a base object used in the query ("FWOBid").
So, for example, if the customer selects objects "FWOBid", "FWOItem", and "FWOSellingOption", I'd want to do this:
var query = from fb in fwoBids
// if "FWOSellingOption", add this join
join so in sellingOptions on fb.Id equals so.BidId
// if "FWOItem", add this join
join i in fwoItems on fb.Id equals i.FWOBidSection.BidId
// select "FWOBid", "FWOItem", and "FWOSellingOption" (everything user has selected)
select new { FWOBid = fb, FWOSellingOption = so, FWOItem = i };
The trick is the customer can select about 6 objects that are all related to each other, resulting in many different combinations of joins. I'd like to avoid hard coding those if possible.
One option is to do some custom join combined with left joins.
A decent TSQL backend should not get any drawbacks in terms of performance for always using all the joins, since the optimers would just remove the join if the condition is always false. But this should be checked out.
bool joinA = true;
bool joinB = false;
bool joinC = true;
var query = from fb in fwoBids
join so in sellingOptions on new { fb.Id, Select = true } equals new { Id = so.BidId, Select = joinA } into js
from so in js.DefaultIfEmpty()
join i in fwoItems on new { fb.Id, Select = true } equals new { Id = i.FWOBidSection.BidId, Select = joinB } into ji
from i in ji.DefaultIfEmpty()
join c in itemsC on new { fb.Id, Select = true } equals new { Id = c.BidId, Select = joinC }
select new
{
FWOBid = fb,
FWOSellingOption = so,
FWOItem = i,
ItemC = c
};
In the Linq query syntax this is not possible, or looking at the other answers hardly readable. Not much more readable but another possibility would be to use the extension methods (sort of pseudo code):
bool condition1;
bool condition2;
List<Bid> bids = new List<Bid>();
List<SellingOption> sellingOptions = new List<SellingOption>();
List<Item> items = new List<Item>();
var result = bids.Select(x => new {bid = x, sellingOption = (SellingOption)null, item = (Item)null});
if (condition1)
result = result.Join(
sellingOptions,
x => x.bid.Id,
x => x.BidId,
(x, sellingOption) => new { x.bid, sellingOption, item = (Item)null });
if (condition2)
result = result.Join(
items,
x => x.bid.Id,
x => x.BidId,
(x, item) => new { x.bid, x.sellingOption, item });
Just see this as a sort of a concept. It is essentially the same that Peter Duniho did.
The thing is, if you don't want to immediately join on all options if not necessary, then it won't look that nice. Perhaps you should try to join all now and don't worry about performance. Have you ever measured how slow or fast it might be? Think of it as "I don't need it now!". If performance is indeed a problem, then you can act on it. But if it is not, and you won't know if you never tried, then leave it as the six joins you mentioned.
It's hard to provide a really good example solution without a really good example problem. However, what I mean by "chain the queries" is something like this:
var query = from x in dba select new { A = x, B = (B)null, C = (C)null };
if ((joinType & JoinType.B) != 0)
{
query = from x in query
join y in dbb on x.A.Id equals y.Id
select new { A = x.A, B = y, C = x.C };
}
if ((joinType & JoinType.C) != 0)
{
query = from x in query
join y in dbc on x.A.Id equals y.Id
select new { A = x.A, B = x.B, C = y };
}
That is, based on the appropriate condition, query the previous result with another join. Note that to do this successfully, each query must produce the same type. Otherwise, it's not possible to assign a new query to the previous query result variable.
Note that while in the above, I simply have a separate property for each possible input type, I could have instead had the type simply have properties for the input columns, Id, Name, and then the Text properties from the B and C types (which would have to be named differently in the query result type, e.g. TextB and TextC). That would look like this:
var query = from x in dba select new { Id = x.Id, Name = x.Name,
TextB = (string)null, TextC = (string)null };
if ((joinType & JoinType.B) != 0)
{
query = from x in query
join y in dbb on x.Id equals y.Id
select new { Id = x.Id, Name = x.Name, TextB = y.Text, TextC = x.TextC };
}
if ((joinType & JoinType.C) != 0)
{
query = from x in query
join y in dbc on x.Id equals y.Id
select new { Id = x.Id, Name = x.Name, TextB = x.TextB, TextC = y.Text };
}
Here is a complete code example that includes the above logic in a runnable program:
class A
{
public string Name { get; private set; }
public int Id { get; private set; }
public A(string name, int id)
{
Name = name;
Id = id;
}
public override string ToString()
{
return "{" + Name + ", " + Id + "}";
}
}
class B
{
public int Id { get; private set; }
public string Text { get; private set; }
public B(int id, string text)
{
Id = id;
Text = text;
}
public override string ToString()
{
return "{" + Id + ", " + Text + "}";
}
}
class C
{
public int Id { get; private set; }
public string Text { get; private set; }
public C(int id, string text)
{
Id = id;
Text = text;
}
public override string ToString()
{
return "{" + Id + ", " + Text + "}";
}
}
[Flags]
enum JoinType
{
None = 0,
B = 1,
C = 2,
BC = 3
}
class Program
{
static void Main(string[] args)
{
A[] dba =
{
new A("A1", 1),
new A("A2", 2),
new A("A3", 3)
};
B[] dbb =
{
new B(1, "B1"),
new B(2, "B2"),
new B(3, "B3")
};
C[] dbc =
{
new C(1, "C1"),
new C(2, "C2"),
new C(3, "C3")
};
JoinType joinType;
while ((joinType = _PromptJoinType()) != JoinType.None)
{
var query = from x in dba select new { A = x, B = (B)null, C = (C)null };
if ((joinType & JoinType.B) != 0)
{
query = from x in query
join y in dbb on x.A.Id equals y.Id
select new { A = x.A, B = y, C = x.C };
}
if ((joinType & JoinType.C) != 0)
{
query = from x in query
join y in dbc on x.A.Id equals y.Id
select new { A = x.A, B = x.B, C = y };
}
foreach (var item in query)
{
Console.WriteLine(item);
}
Console.WriteLine();
}
}
private static JoinType _PromptJoinType()
{
JoinType? joinType = null;
do
{
Console.Write("Join type ['A' for all, 'B', 'C', or 'N' for none]");
ConsoleKeyInfo key = Console.ReadKey();
Console.WriteLine();
switch (key.Key)
{
case ConsoleKey.A:
joinType = JoinType.BC;
break;
case ConsoleKey.B:
joinType = JoinType.B;
break;
case ConsoleKey.C:
joinType = JoinType.C;
break;
case ConsoleKey.N:
joinType = JoinType.None;
break;
default:
break;
}
} while (joinType == null);
return joinType.Value;
}
}
I hope this is an improvement over previous answers.
public class Bids
{
public int Id { get; set; }
public double Price { get; set; }
}
public class BidSection
{
public int BidId { get; set; }
}
public class SellingOptions
{
public int BidId { get; set; }
public int Quantity { get; set; }
}
public class Item
{
public int ItemId { get; set; }
public BidSection FWOBidSection { get; set; }
}
public class ConditionalJoin
{
public bool jOpt1 { get; set; }
public bool jOpt2 { get; set; }
public ConditionalJoin(bool _joinOption1, bool _joinOption2)
{
jOpt1 = _joinOption1;
jOpt2 = _joinOption2;
}
public class FBandSo
{
public Bids FWOBids { get; set; }
public SellingOptions FWOSellingOptions { get; set; }
}
public class FBandI
{
public Bids FWOBids { get; set; }
public Item FWOItem { get; set; }
}
public void Run()
{
var fwoBids = new List<Bids>();
var sellingOptions = new List<SellingOptions>();
var fwoItems = new List<Item>();
fwoBids.Add(new Bids() { Id = 1, Price = 1.5 });
sellingOptions.Add(new SellingOptions() { BidId = 1, Quantity = 2 });
fwoItems.Add(new Item() { ItemId = 10, FWOBidSection = new BidSection() { BidId = 1 } });
IQueryable<Bids> fb = fwoBids.AsQueryable();
IQueryable<SellingOptions> so = sellingOptions.AsQueryable();
IQueryable<Item> i = fwoItems.AsQueryable();
IQueryable<FBandSo> FBandSo = null;
IQueryable<FBandI> FBandI = null;
if (jOpt1)
{
FBandSo = from f in fb
join s in so on f.Id equals s.BidId
select new FBandSo()
{
FWOBids = f,
FWOSellingOptions = s
};
}
if (jOpt2)
{
FBandI = from f in fb
join y in i on f.Id equals y.FWOBidSection.BidId
select new FBandI()
{
FWOBids = f,
FWOItem = y
};
}
if (jOpt1 && jOpt2)
{
var query = from j1 in FBandSo
join j2 in FBandI
on j1.FWOBids.Id equals j2.FWOItem.FWOBidSection.BidId
select new
{
FWOBids = j1.FWOBids,
FWOSellingOptions = j1.FWOSellingOptions,
FWOItems = j2.FWOItem
};
}
}
}

How do I match two identical database tables with LINQ?

I want to match 2 identical tables:
sourceProducts (productName, ProductionDate, ManID, shipper, distributer)
CommProducts (productName, ProductionDate, ManID, shipper, distributer)
but the number of rows and the record contents may differ. How do I select a certain record = raw from one table and get its clone record from the other table (e.g., check if the same record exists)? How do I do this using LinQ?
UPDATE: Here's the LINQ code:
protected void checkBtn_Click(object sender, EventArgs e)
{
MyProductsDataContext mySdb = new MyProductsDataContext();
Product mypro = new Product { ManId = int.Parse(TxtManI.Text), ProductName = TxtProN.Text, ProductionDate =DateTime .Parse ( TxtProDat.Text), Shipper = TxtShipI.Text, Distributer = TxtDistI.Text };
var spro = (from p in mySdb.Products
select new { p.ManId, p.ProductName, p.ProductionDate, p.Shipper, p.Distributer }).
Intersect(from s in mySdb.SourceProducts select new { s.ManId, s.ProductName, s.ProductionDate, s.Shipper, s.Distributer });
if (spro != null)
{
LblMessage.Text = "Acceptable product Data Inserted Sucessfully";
InsertData();
}
else
{
LblMessage.Text = "Invalid Product or bad Entry Please retype";
}
}
I would join on ManId and then compare the rest of the values in a where clause:
bool productExists = (
from p in mySdb.Products
join s in mySdb.SourceProducts
on p.ManId equals s.ManId
where p.ProductName == s.ProductName
&& p.ProductionDate == s.ProductionDate
&& p.Shipper == s.Shipper
&& p.Distributer = s.Distributer
select new { p.ManId, p.ProductName, p.ProductionDate, p.Shipper, p.Distributer }
).Any();
if (productExists)
{
LblMessage.Text = "Acceptable product Data Inserted Sucessfully";
InsertData();
}
else
{
LblMessage.Text = "Invalid Product or bad Entry Please retype";
}
I've used Any() to produce an efficient EXISTS SQL query. You could use SingleOrDefault() or FirstOrDefault() instead if you actually need to use the product returned.
I also don't see anywhere that you're using your new Product's ID - you might need to add that filter to the query as well:
Product mypro = new Product { ... };
bool productExists = (
from p in mySdb.Products
where p.ManId equals mypro.ManId
join s in mySdb.SourceProducts
on p.ManId equals s.ManId
...
You can probably do this using a join but I've hobbled together a unit test which shows one way to this
public class TestProduct
{
public int ManId { get; set; }
public string ProductName { get; set; }
public DateTime ProductionDate { get; set; }
public string Shipper { get; set; }
public string Distributor { get; set; }
}
[TestMethod]
public void TestSourceTable()
{
// Set up a test list
var list = new List<TestProduct>();
for (int i=0;i<5;i++)
{
var p = new TestProduct
{
Distributor = "D" + i,
ManId = i,
ProductionDate = DateTime.Now,
ProductName = "P" + i,
Shipper = "S" + i
};
list.Add(p);
}
// Get an existing product
var existingProduct = list[4];
// Get an unknown product
var unknownProduct = new TestProduct()
{
ManId = -1,
Distributor = "",
ProductionDate = DateTime.Now.AddDays(-1),
ProductName = "",
Shipper = ""
};
// product found
Assert.True(list.Any(p => p == existingProduct));
// product not found
Assert.False(list.Any(p => p == unknownProduct));
}

Categories

Resources