我有两张表,一张称为 Companies,另一张称为 Locations。Companies 有 Id 和 Name,Locations 有 Id、CompanyId、Name 和 SubAccount。我有两个项目。一种是 IMS.Data,所有验证都在其中,而 IMS 则在 Web 表单页面所在的位置。我无法验证公司是否有位置(如果公司 ID 是任何地方的外键),则不要删除记录。这是我到目前为止所拥有的一切,但我无法引用 Locations CompanyId 以使用 lambda 表达式进行检查。谁能帮助我我是 lambda 表达式的新手。
这是我用于验证的方法
namespace IMS.Data
{
public class CompanyContext : IMSDBContext
{
public Company DeleteCompany(Company company)
{
if (company.Name == null)
{
throw new Exception("Please select a record to delete.");
}
if (Companies.Any(x => x.Name == company.Name))
{
throw new Exception("Can not delete a company that has a location.");
}
Companies.Remove(company);
return company;
}
}
}
这是我使用的删除按钮
namespace IMS
{
public partial class CompanySetUp : Page
{
private const string AddButton = "Add";
private const string SaveButton = "Save";
private const string DeleteButton = "Delete";
private const string CancelButton = "Cancel";
private int CompanyId // This puts the "CompanyId" into a viewstate and is used to update the record
{
get
{
return (int)ViewState["_companyId"];
}
set
{
ViewState["_companyId"] = value;
}
}
private IList<Company> Companies { get; set; } // This gets and sets the list of companies from the table "Companies"
protected void Page_Load(object sender, EventArgs e)
{
PopulateCompanyListGrid();
//if (Companies != null && Companies.Count > 0) // This will put a record in the "txtCompanyName.Text" on page load
//{
// txtCompanyName.Text = Companies.First().Name;
//}
}
protected void btnDelete_Click(object sender, EventArgs e) // This will delete the record that matches the textbox or throw an exception
{
CompanyContext context = null;
switch (btnDelete.Text)
{
case DeleteButton:
try
{
context = new CompanyContext();
var company = context.Companies.ToList().First(x => x.Name == txtCompanyName.Text);
context.DeleteCompany(company);
//PopulateCompanyListGrid();
Reload();
}
catch (Exception ex)
{
lblCompanyNameNotification.Text = ex.Message;
}
finally
{
if (context != null)
{
context.Dispose();
}
}
PopulateCompanyListGrid();
break;
case CancelButton:
Reload();
break;
}
}