ObjectDataSource connection - c#

I'm trying to work through Pluralsights ASP.NET Webforms (c#) demos and cannot figure out why my class in my app_code folder will not show in my ObjectDataSource dropdown list when trying to create a new Datasource connection. I've been stuck on this for nearly a week and a half and am new to programming so don't understand all of the lingo after searching for helpful documents. I don't know where to implement what.
Here's the code for my BAL.cs class located in my App_Code Folder and I have a Data folder with a Linq to class connection named Northwind.
// Here is my code for BAL.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Globalization;
using Northwind;
public class BAL
{
public List<String> GetCountries()
{
using (var context = new NorthwindDataContext())
{
return (from c in context.Customers
select c.Country).Distinct().ToList();
}
}
public List<Customer> GetCustomersByCountry(string country)
{
using (var context = new NorthwindDataContext())
{
return (from c in context.Customers
where c.Country == country
select c).ToList();
}
}
public Customer GetCustomer(string custID)
{
using (var context = new NorthwindDataContext())
{
return (from c in context.Customers
where c.CustomerID == custID
select c).SingleOrDefault();
}
}
}
}
Now the designer.cs for my Northwind.dbml file
#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.17929
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Northwind
{
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using System.ComponentModel;
using System;
[global::System.Data.Linq.Mapping.DatabaseAttribute(Name="Northwind")]
public partial class NorthwindDataContext : System.Data.Linq.DataContext
{
private static System.Data.Linq.Mapping.MappingSource mappingSource = new
AttributeMappingSource();
#region Extensibility Method Definitions
partial void OnCreated();
partial void InsertCustomer(Customer instance);
partial void UpdateCustomer(Customer instance);
partial void DeleteCustomer(Customer instance);
#endregion
public NorthwindDataContext() :
base
(global::System.Configuration.ConfigurationManager.ConnectionStrings
["NorthwindConnectionString"].ConnectionString, mappingSource)
{
OnCreated();
}
public NorthwindDataContext(string connection) :
base(connection, mappingSource)
{
OnCreated();
}
public NorthwindDataContext(System.Data.IDbConnection connection) :
base(connection, mappingSource)
{
OnCreated();
}
public NorthwindDataContext(string connection,
System.Data.Linq.Mapping.MappingSource mappingSource) :
base(connection, mappingSource)
{
OnCreated();
}
public NorthwindDataContext(System.Data.IDbConnection connection,
System.Data.Linq.Mapping.MappingSource mappingSource) :
base(connection, mappingSource)
{
OnCreated();
}
public System.Data.Linq.Table<Customer> Customers
{
get
{
return this.GetTable<Customer>();
}
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Customers")]
public partial class Customer : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new
PropertyChangingEventArgs(String.Empty);
private string _CustomerID;
private string _CompanyName;
private string _ContactName;
private string _ContactTitle;
private string _Address;
private string _City;
private string _Region;
private string _PostalCode;
private string _Country;
private string _Phone;
private string _Fax;
private string _Image;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnCustomerIDChanging(string value);
partial void OnCustomerIDChanged();
partial void OnCompanyNameChanging(string value);
partial void OnCompanyNameChanged();
partial void OnContactNameChanging(string value);
partial void OnContactNameChanged();
partial void OnContactTitleChanging(string value);
partial void OnContactTitleChanged();
partial void OnAddressChanging(string value);
partial void OnAddressChanged();
partial void OnCityChanging(string value);
partial void OnCityChanged();
partial void OnRegionChanging(string value);
partial void OnRegionChanged();
partial void OnPostalCodeChanging(string value);
partial void OnPostalCodeChanged();
partial void OnCountryChanging(string value);
partial void OnCountryChanged();
partial void OnPhoneChanging(string value);
partial void OnPhoneChanged();
partial void OnFaxChanging(string value);
partial void OnFaxChanged();
partial void OnImageChanging(string value);
partial void OnImageChanged();
#endregion
public Customer()
{
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_CustomerID",
DbType="NChar(5) NOT NULL", CanBeNull=false, IsPrimaryKey=true)]
public string CustomerID
{
get
{
return this._CustomerID;
}
set
{
if ((this._CustomerID != value))
{
this.OnCustomerIDChanging(value);
this.SendPropertyChanging();
this._CustomerID = value;
this.SendPropertyChanged("CustomerID");
this.OnCustomerIDChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_CompanyName",
DbType="NVarChar(40) NOT NULL", CanBeNull=false)]
public string CompanyName
{
get
{
return this._CompanyName;
}
set
{
if ((this._CompanyName != value))
{
this.OnCompanyNameChanging(value);
this.SendPropertyChanging();
this._CompanyName = value;
this.SendPropertyChanged("CompanyName");
this.OnCompanyNameChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ContactName",
DbType="NVarChar(30)")]
public string ContactName
{
get
{
return this._ContactName;
}
set
{
if ((this._ContactName != value))
{
this.OnContactNameChanging(value);
this.SendPropertyChanging();
this._ContactName = value;
this.SendPropertyChanged("ContactName");
this.OnContactNameChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ContactTitle",
DbType="NVarChar(30)")]
public string ContactTitle
{
get
{
return this._ContactTitle;
}
set
{
if ((this._ContactTitle != value))
{
this.OnContactTitleChanging(value);
this.SendPropertyChanging();
this._ContactTitle = value;
this.SendPropertyChanged("ContactTitle");
this.OnContactTitleChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Address",
DbType="NVarChar(60)")]
public string Address
{
get
{
return this._Address;
}
set
{
if ((this._Address != value))
{
this.OnAddressChanging(value);
this.SendPropertyChanging();
this._Address = value;
this.SendPropertyChanged("Address");
this.OnAddressChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_City",
DbType="NVarChar(15)")]
public string City
{
get
{
return this._City;
}
set
{
if ((this._City != value))
{
this.OnCityChanging(value);
this.SendPropertyChanging();
this._City = value;
this.SendPropertyChanged("City");
this.OnCityChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Region",
DbType="NVarChar(15)")]
public string Region
{
get
{
return this._Region;
}
set
{
if ((this._Region != value))
{
this.OnRegionChanging(value);
this.SendPropertyChanging();
this._Region = value;
this.SendPropertyChanged("Region");
this.OnRegionChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_PostalCode",
DbType="NVarChar(10)")]
public string PostalCode
{
get
{
return this._PostalCode;
}
set
{
if ((this._PostalCode != value))
{
this.OnPostalCodeChanging(value);
this.SendPropertyChanging();
this._PostalCode = value;
this.SendPropertyChanged("PostalCode");
this.OnPostalCodeChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Country",
DbType="NVarChar(15)")]
public string Country
{
get
{
return this._Country;
}
set
{
if ((this._Country != value))
{
this.OnCountryChanging(value);
this.SendPropertyChanging();
this._Country = value;
this.SendPropertyChanged("Country");
this.OnCountryChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Phone",
DbType="NVarChar(24)")]
public string Phone
{
get
{
return this._Phone;
}
set
{
if ((this._Phone != value))
{
this.OnPhoneChanging(value);
this.SendPropertyChanging();
this._Phone = value;
this.SendPropertyChanged("Phone");
this.OnPhoneChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Fax",
DbType="NVarChar(24)")]
public string Fax
{
get
{
return this._Fax;
}
set
{
if ((this._Fax != value))
{
this.OnFaxChanging(value);
this.SendPropertyChanging();
this._Fax = value;
this.SendPropertyChanged("Fax");
this.OnFaxChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Image",
DbType="NVarChar(50)")]
public string Image
{
get
{
return this._Image;
}
set
{
if ((this._Image != value))
{
this.OnImageChanging(value);
this.SendPropertyChanging();
this._Image = value;
this.SendPropertyChanged("Image");
this.OnImageChanged();
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new
PropertyChangedEventArgs (propertyName));
}
}
}
}
#pragma warning restore 1591

If they're not showing up in the GUI, try manually specifying which methods go with which actions.
Eg:
[DataObjectMethod(DataObjectMethodType.Select, true)]
[DataObjectMethod(DataObjectMethodType.Insert, true)]
[DataObjectMethod(DataObjectMethodType.Update, true)]
[DataObjectMethod(DataObjectMethodType.Delete, true)]
More info here.

You need to make sure your project type is a Web project, otherwise Visual Studio will not consider the App_Code folder
Make sure you include System.Data.Linq as a reference in your Web.Config file bz adding the following
<assemblies>
<add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
Following is the Web.Config file content. I got the content from the exercise files on the Introduction to ASP.NET 4 WebForms course from pluralsight:

See comments here: stackoverflow.com/questions/16170156/
I think adding an assembly ref to web.config solved the problem for me.

Related

ExtensionDataObject showing up in service reference

I'm writing a WCF service and the ExtensionDataObject shows up in my Reference.cs file of the service reference even though I don't have it defined in my data class.
I know what the ExtensionDataObject is for, but do not want to use it.
I don't know why it's showing up... Can somebody tell me how to not include it in my service reference? Additionally, there is an OptionalFieldAttribute which is declared in my service reference which again is not part of my data class. How can I remove this as well?
Here is the generated service reference declaration on my client:
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="User", Namespace="http://www.Ryder.com/SOA/DataContracts/2014/02/17")]
[System.SerializableAttribute()]
public partial class User : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {
[System.NonSerializedAttribute()]
private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string PasswordField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private Ryder.ShopProcessService.Outbound.ShopProcessService.Permissions PermissionsField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string UserIDField;
[System.Runtime.Serialization.OptionalFieldAttribute()]
private Ryder.ShopProcessService.Outbound.ShopProcessService.UserTypeEnum UserTypeField;
[global::System.ComponentModel.BrowsableAttribute(false)]
public System.Runtime.Serialization.ExtensionDataObject ExtensionData {
get {
return this.extensionDataField;
}
set {
this.extensionDataField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string Password {
get {
return this.PasswordField;
}
set {
if ((object.ReferenceEquals(this.PasswordField, value) != true)) {
this.PasswordField = value;
this.RaisePropertyChanged("Password");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public Ryder.ShopProcessService.Outbound.ShopProcessService.Permissions Permissions {
get {
return this.PermissionsField;
}
set {
if ((object.ReferenceEquals(this.PermissionsField, value) != true)) {
this.PermissionsField = value;
this.RaisePropertyChanged("Permissions");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string UserID {
get {
return this.UserIDField;
}
set {
if ((object.ReferenceEquals(this.UserIDField, value) != true)) {
this.UserIDField = value;
this.RaisePropertyChanged("UserID");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public Ryder.ShopProcessService.Outbound.ShopProcessService.UserTypeEnum UserType {
get {
return this.UserTypeField;
}
set {
if ((this.UserTypeField.Equals(value) != true)) {
this.UserTypeField = value;
this.RaisePropertyChanged("UserType");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
Here is the corresponding class declaration in my service project: Note that I just changed the namespace to "abc" for privacy...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.ServiceModel;
namespace abc.Enterprise.DataTransferObjects
{
[Serializable, DataContract(Name = "User", Namespace = "http://www.abc.com/SOA/DataContracts/2014/02/17")]
public class User
{
private UserTypeEnum userType;
private string userID;
private string password;
private Permissions permissions;
public User()
{
}
[DataMember(Name = "UserType")]
public UserTypeEnum UserType
{
get
{
return userType;
}
set
{
userType = value;
}
}
[DataMember(Name = "UserID")]
public string UserID
{
get
{
return userID;
}
set
{
userID = value;
}
}
[DataMember(Name = "Password")]
public string Password
{
get
{
return password;
}
set
{
password = value;
}
}
[DataMember(Name = "Permissions")]
public Permissions Permissions
{
get
{
return permissions;
}
set
{
permissions = value;
}
}
}
}

A first chance exception of type 'System.Data.SqlServerCe.SqlCeException' occurred in Microsoft.Phone.Data.Internal.ni.dll

I have added a new column to my database table. When I have added this new columnm, the first chance exception start appearing. When I debugged it, it stated the code line
MLongListSelector.ItemsSource = c.ToDoList.ToList();
is the next statement to execute that causes the problem. What have I done wrong there?
using (DatabaseContext c = new DatabaseContext(DatabaseContext.ConnectionString))
{
c.CreateIfNotExists();
c.LogDebug = true;
//output todolist data from database
MLongListSelector.ItemsSource = c.ToDoList.ToList();
}
stack trace of that line:
ex.StackTrace " at System.Data.SqlServerCe.SqlCeCommand.ProcessResults(Int32 hr)\r\n at System.Data.SqlServerCe.SqlCeCommand.CompileQueryPlan()\r\n at System.Data.SqlServerCe.SqlCeCommand.ExecuteCommand(CommandBehavior behavior, String method, ResultSetOptions options)\r\n at System.Data.SqlServerCe.SqlCeCommand.ExecuteDbDataReader(CommandBehavior behavior)\r\n at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult, Boolean isCompiledQuery)\r\n at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries, Boolean isCompiledQuery)\r\n at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)\r\n at System.Data.Linq.Table`1.GetEnumerator()\r\n at System.Data.Linq.Table`1.System.Collections.Generic.IEnumerable<TEntity>.GetEnumerator()\r\n at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)\r\n at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)\r\n at PhoneApp.MainPage.OnNavigatedTo(NavigationEventArgs e)"
e.message:
ex.Message "The column name is not valid. [ Node name (if any) = t0,Column name = Col ]" string
Get and Set:
public partial class ToDoList : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _Id;
private string _Title;
private string _Description;
private string _Col;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnIdChanging(int value);
partial void OnIdChanged();
partial void OnTitleChanging(string value);
partial void OnTitleChanged();
partial void OnDescriptionChanging(string value);
partial void OnDescriptionChanged();
partial void OnColChanging(string value);
partial void OnColChanged();
#endregion
public ToDoList()
{
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Id", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public int Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this.OnIdChanging(value);
this.SendPropertyChanging();
this._Id = value;
this.SendPropertyChanged("Id");
this.OnIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Title", DbType="NVarChar(100) NOT NULL", CanBeNull=false)]
public string Title
{
get
{
return this._Title;
}
set
{
if ((this._Title != value))
{
this.OnTitleChanging(value);
this.SendPropertyChanging();
this._Title = value;
this.SendPropertyChanged("Title");
this.OnTitleChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Description", DbType="NVarChar(100)")]
public string Description
{
get
{
return this._Description;
}
set
{
if ((this._Description != value))
{
this.OnDescriptionChanging(value);
this.SendPropertyChanging();
this._Description = value;
this.SendPropertyChanged("Description");
this.OnDescriptionChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Col", DbType="NVarChar(25)")]
public string Col
{
get
{
return this._Col;
}
set
{
if ((this._Col != value))
{
this.OnColChanging(value);
this.SendPropertyChanging();
this._Col = value;
this.SendPropertyChanged("Col");
this.OnColChanged();
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
I just tried your solution and i don't see why it should not work. Do you have the ToDoList marked with a "Table attribute"? i.e.
[Table]
public partial class ToDoList : INotifyPropertyChanging, INotifyPropertyChanged
Also, it might be worth you dropping the database and recreating it. Follow the code sample below and try to go from there. if this does not work then feel free to attach a simple project that replicates the issue.
Xaml
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox x:Name="lstToDos">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Title}"></TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
Code behind
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
using (DatabaseContext c = new DatabaseContext(DatabaseContext.ConnectionString))
{
c.CreateIfNotExists();
//Add new records for debug sake:
var dateNow = DateTime.UtcNow.TimeOfDay.ToString();
var newToDo = new ToDoList { Col = "Col" + dateNow, Description = "Some description" + dateNow, Title = "Some title" + dateNow };
c.ToDoLists.InsertOnSubmit(newToDo);
c.SubmitChanges();
lstToDos.ItemsSource = c.ToDoLists.ToList();
}
}
}
Data context file
public class DatabaseContext : DataContext
{
public DatabaseContext(string connectionString)
: base(connectionString)
{
}
public Table<ToDoList> ToDoLists
{
get
{
return this.GetTable<ToDoList>();
}
}
public void CreateIfNotExists()
{
if (!this.DatabaseExists())
{
this.CreateDatabase();
}
}
public const string ConnectionString = #"isostore:/MyDatabases.sdf";
}
ToDO entity
[Table]
public partial class ToDoList : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _Id;
private string _Title;
private string _Description;
private string _Col;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnIdChanging(int value);
partial void OnIdChanged();
partial void OnTitleChanging(string value);
partial void OnTitleChanged();
partial void OnDescriptionChanging(string value);
partial void OnDescriptionChanged();
partial void OnColChanging(string value);
partial void OnColChanged();
#endregion
public ToDoList()
{
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_Id", AutoSync = AutoSync.OnInsert, DbType = "Int NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true)]
public int Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this.OnIdChanging(value);
this.SendPropertyChanging();
this._Id = value;
this.SendPropertyChanged("Id");
this.OnIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_Title", DbType = "NVarChar(100) NOT NULL", CanBeNull = false)]
public string Title
{
get
{
return this._Title;
}
set
{
if ((this._Title != value))
{
this.OnTitleChanging(value);
this.SendPropertyChanging();
this._Title = value;
this.SendPropertyChanged("Title");
this.OnTitleChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_Description", DbType = "NVarChar(100)")]
public string Description
{
get
{
return this._Description;
}
set
{
if ((this._Description != value))
{
this.OnDescriptionChanging(value);
this.SendPropertyChanging();
this._Description = value;
this.SendPropertyChanged("Description");
this.OnDescriptionChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_Col", DbType = "NVarChar(25)")]
public string Col
{
get
{
return this._Col;
}
set
{
if ((this._Col != value))
{
this.OnColChanging(value);
this.SendPropertyChanging();
this._Col = value;
this.SendPropertyChanged("Col");
this.OnColChanged();
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}

Drop down shows each record several times

i am picking list of names from database, according to scenario each name exists many times in database, That's ok. Now i have filled a DROPDOWNLIST with those names but in drop down list each name appears several times:
but i want to display each name 1 time in DROPDOWN. I have used distict() but not working.
USING MVC 3, Linq to SQL
Controller:
namespace EmployeeAttendance_app.Controllers
{
public class HomeController : Controller
{
EmployeeAtdDataContext DataContext = new EmployeeAtdDataContext();
public ActionResult Index()
{
ViewBag.Message = "Precise Technology Consultants";
//var EmployeeAtd = DataContext.GetAttendance_Sp();
IEnumerable<GetAtdRecord_SpResult> EmployeeAtd = DataContext.GetAtdRecord_Sp(null).ToList();
var names = (from n in DataContext.EmployeeAtds select n).Distinct();
//ViewData["EmplID"] = new SelectList(names, "EmplID", "EmplName");
return View(EmployeeAtd);
}
public ActionResult ddl()
{
var names = (from n in DataContext.EmployeeAtds select n).Distinct();
ViewData["EmplID"] = new SelectList(names, "EmplID", "EmplName");
return View();
}
public ActionResult showDDL(string EmplID)
{
ViewBag.EmplID = EmplID;
return View();
}
public ActionResult About()
{
return View();
}
Views:
#{
ViewBag.Title = "ddl";
}
<h2>ddl</h2>
#using (Html.BeginForm("showDDL", "Home", FormMethod.Get))
{
<fieldset>
Employers
#Html.DropDownList("EmplID", "Select Name")
<p>
<input type="submit" value="Submit" />
</p>
</fieldset>
}
ModeL
amespace EmployeeAttendance_app.Models
{
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using System.ComponentModel;
using System;
[global::System.Data.Linq.Mapping.DatabaseAttribute(Name="a1")]
public partial class EmployeeAtdDataContext : System.Data.Linq.DataContext
{
private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();
#region Extensibility Method Definitions
partial void OnCreated();
#endregion
public EmployeeAtdDataContext() :
base(global::System.Configuration.ConfigurationManager.ConnectionStrings["a1ConnectionString"].ConnectionString, mappingSource)
{
OnCreated();
}
public EmployeeAtdDataContext(string connection) :
base(connection, mappingSource)
{
OnCreated();
}
public EmployeeAtdDataContext(System.Data.IDbConnection connection) :
base(connection, mappingSource)
{
OnCreated();
}
public EmployeeAtdDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
base(connection, mappingSource)
{
OnCreated();
}
public EmployeeAtdDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
base(connection, mappingSource)
{
OnCreated();
}
public System.Data.Linq.Table<EmployeeAtd> EmployeeAtds
{
get
{
return this.GetTable<EmployeeAtd>();
}
}
[global::System.Data.Linq.Mapping.FunctionAttribute(Name="dbo.GetAtdRecord_Sp")]
public ISingleResult<GetAtdRecord_SpResult> GetAtdRecord_Sp([global::System.Data.Linq.Mapping.ParameterAttribute(Name="EmplID", DbType="Int")] System.Nullable<int> emplID)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), emplID);
return ((ISingleResult<GetAtdRecord_SpResult>)(result.ReturnValue));
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.V_EmployeeAtd")]
public partial class EmployeeAtd
{
private string _EmplID;
private string _EmplName;
private string _RecDate;
private string _RecTime;
private string _DeptName;
public EmployeeAtd()
{
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_EmplID", DbType="Char(8) NOT NULL", CanBeNull=false)]
public string EmplID
{
get
{
return this._EmplID;
}
set
{
if ((this._EmplID != value))
{
this._EmplID = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_EmplName", DbType="NVarChar(40) NOT NULL", CanBeNull=false)]
public string EmplName
{
get
{
return this._EmplName;
}
set
{
if ((this._EmplName != value))
{
this._EmplName = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_RecDate", DbType="Char(10)")]
public string RecDate
{
get
{
return this._RecDate;
}
set
{
if ((this._RecDate != value))
{
this._RecDate = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_RecTime", DbType="Char(5)")]
public string RecTime
{
get
{
return this._RecTime;
}
set
{
if ((this._RecTime != value))
{
this._RecTime = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DeptName", DbType="NVarChar(50)")]
public string DeptName
{
get
{
return this._DeptName;
}
set
{
if ((this._DeptName != value))
{
this._DeptName = value;
}
}
}
}
public partial class GetAtdRecord_SpResult
{
private string _EmplID;
private string _EmplName;
private string _InTime;
private string _OutTime;
private string _DateVisited;
private string _TimeWorked;
private string _OverTime;
public GetAtdRecord_SpResult()
{
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_EmplID", DbType="Char(8) NOT NULL", CanBeNull=false)]
public string EmplID
{
get
{
return this._EmplID;
}
set
{
if ((this._EmplID != value))
{
this._EmplID = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_EmplName", DbType="NVarChar(40) NOT NULL", CanBeNull=false)]
public string EmplName
{
get
{
return this._EmplName;
}
set
{
if ((this._EmplName != value))
{
this._EmplName = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_InTime", DbType="Char(5)")]
public string InTime
{
get
{
return this._InTime;
}
set
{
if ((this._InTime != value))
{
this._InTime = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_OutTime", DbType="Char(5)")]
public string OutTime
{
get
{
return this._OutTime;
}
set
{
if ((this._OutTime != value))
{
this._OutTime = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DateVisited", DbType="Char(10) NOT NULL", CanBeNull=false)]
public string DateVisited
{
get
{
return this._DateVisited;
}
set
{
if ((this._DateVisited != value))
{
this._DateVisited = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_TimeWorked", DbType="Char(5)")]
public string TimeWorked
{
get
{
return this._TimeWorked;
}
set
{
if ((this._TimeWorked != value))
{
this._TimeWorked = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_OverTime", DbType="VarChar(6)")]
public string OverTime
{
get
{
return this._OverTime;
}
set
{
if ((this._OverTime != value))
{
this._OverTime = value;
}
}
}
}
}
pragma warning restore 1591
I think you are implementing distinct on n which contains all properties of class. You need to apply distinct on required columns only. Like
var empList= DataContext.EmployeeAtds.Select(n => new
{
EmplID= n.EmplID,
EmplName= n.EmplName
}).Distinct().ToList();
OR
var empList= (from n in DataContext.EmployeeAtds select new{ EmplID= n.EmplID,
EmplName= n.EmplName}).Distinct();
You need to make sure that your underlying object overrides GetHashCode and Equals in order for it to work properly.
Please see here for more information:
http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx
As an example, if you have an object called EmployeeAtd it needs to implement the above two methods in order to know when comparative objects are equal.
This is a simple example but you may consider an EmployeeAtd objects the same if they have matching EmplID's, an example Equals override could be:
public override bool Equals(object obj)
{
if (obj == null) return false;
if (this.GetType() != obj.GetType()) return false;
EmployeeAtd emp = (EmployeeAtd) obj;
if (!Object.Equals(EmplID, emp.EmplID)) return false;
return true;
}
If your EmplID is an int you could simply implement the GetHashCode as follows:
public override int GetHashCode ()
{
return EmplID.GetHashCode();
}
This is no way best practice but there are plenty of other questions on how to do this.
What is the best way to implement this composite GetHashCode()
Why is it important to override GetHashCode when Equals method is overridden?
You can use DISTINCT safely, I am not sure where exactly you are facing problem. Please follow this example. Say I Have a database table this way -
Then I write following Stored Procedure
USE [Sample]
GO
CREATE PROCEDURE GiveNames
AS
SELECT DISTINCT(Name) FROM [dbo].[SampleTable]
GO
Then I create a MVC Project and add EDMX and used the content in Controller in following way -
public class EdmxController : Controller
{
//
// GET: /Edmx/
public ActionResult Index()
{
DDLModel model = new DDLModel();
model.Items = new List<string>();
using (var entities = new SampleEntities1())
{
model.Items = entities.GiveNames().ToList();
}
return View(model);
}
}
public class DDLModel
{
public List<String> Items { get; set; }
}
My View -
#model MVC.Controllers.DDLModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div>
#Html.DropDownList("MyDDL",new SelectList(Model.Items), "--Choose any Item--")
</div>
And my output doesn't conduct any duplicates -

How to use MVVM Light With Sql Server Compact - Windows Phone 7?

I am using MVVM Light, Sql Server Compact Toolkit and windows phone 7.
I created a sql server compact 3.5 database and then used the toolkit to generate the datacontext and domain class for each table.
Looks like this
[global::System.Data.Linq.Mapping.TableAttribute(Name = "ContactGroups")]
public partial class ContactGroup : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _Id;
private string _Title;
private System.DateTime _LastUpdated;
private EntitySet<GContact> _GContacts;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnIdChanging(int value);
partial void OnIdChanged();
partial void OnTitleChanging(string value);
partial void OnTitleChanged();
partial void OnLastUpdatedChanging(System.DateTime value);
partial void OnLastUpdatedChanged();
#endregion
public ContactGroup()
{
this._GContacts = new EntitySet<GContact>(new Action<GContact>(this.attach_GContacts), new Action<GContact>(this.detach_GContacts));
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_Id", DbType = "Int NOT NULL", IsPrimaryKey = true)]
public int Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this.OnIdChanging(value);
this.SendPropertyChanging();
this._Id = value;
this.SendPropertyChanged("Id");
this.OnIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_Title", DbType = "NVarChar(100) NOT NULL", CanBeNull = false)]
public string Title
{
get
{
return this._Title;
}
set
{
if ((this._Title != value))
{
this.OnTitleChanging(value);
this.SendPropertyChanging();
this._Title = value;
this.SendPropertyChanged("Title");
this.OnTitleChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_LastUpdated", DbType = "DateTime NOT NULL")]
public System.DateTime LastUpdated
{
get
{
return this._LastUpdated;
}
set
{
if ((this._LastUpdated != value))
{
this.OnLastUpdatedChanging(value);
this.SendPropertyChanging();
this._LastUpdated = value;
this.SendPropertyChanged("LastUpdated");
this.OnLastUpdatedChanged();
}
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name = "FK_GContacts_ContactGroups", Storage = "_GContacts", ThisKey = "Id", OtherKey = "ContactGroups_Id", DeleteRule = "NO ACTION")]
public EntitySet<GContact> GContacts
{
get
{
return this._GContacts;
}
set
{
this._GContacts.Assign(value);
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private void attach_GContacts(GContact entity)
{
this.SendPropertyChanging();
entity.ContactGroup = this;
}
private void detach_GContacts(GContact entity)
{
this.SendPropertyChanging();
entity.ContactGroup = null;
}
}
Yet when I try to make it blendable(ie make fake data so when I go into blend I can work with it better instead of looking at empty boxes) nothing shows up in blend
when I have a simple domain without it works
public class ContactGroup
{
public int Id { get; set; }
public string Title { get; set; }
public DateTime LastUpdated { get; set; }
public List<GContacts> Contacts { get; set; }
public ContactGroup()
{
Contacts = new List<GContacts>();
}
}
Then in my viewmodel locator I would have
if (ViewModelBase.IsInDesignModeStatic)
{
SimpleIoc.Default.Register<IContactService, DesignContactService>();
}
else
{
SimpleIoc.Default.Register<IContactService, DesignContactService>();
}
Edit
The problem line seens to be this
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
When I remove it then blend shows the data again.

Equal is not defined between type Nullable<Int32> and Int32

I am writing a boring application to manage patients and their clinic history. I used SQLite combined with DbLinq libraries and DbMetal code generation utility. Here are two classes from the genereated code extracted from the underlying database:
[Table(Name="main.Patients")]
public partial class Patient : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged
{
private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");
private long _birthday;
private string _firstName;
private int _hasChildren;
private System.Nullable<int> _id;
private int _isMarried;
private string _lastName;
private string _profession;
private EntitySet<ClinicCase> _clinicCases;
private EntitySet<PatientAddress> _patientsAddresses;
private EntitySet<PatientPhoneNumber> _patientsPhoneNumbers;
#region Extensibility Method Declarations
partial void OnCreated();
partial void OnBirthdayChanged();
partial void OnBirthdayChanging(long value);
partial void OnFirstNameChanged();
partial void OnFirstNameChanging(string value);
partial void OnHasChildrenChanged();
partial void OnHasChildrenChanging(int value);
partial void OnIDChanged();
partial void OnIDChanging(System.Nullable<int> value);
partial void OnIsMarriedChanged();
partial void OnIsMarriedChanging(int value);
partial void OnLastNameChanged();
partial void OnLastNameChanging(string value);
partial void OnProfessionChanged();
partial void OnProfessionChanging(string value);
#endregion
public Patient()
{
_clinicCases = new EntitySet<ClinicCase>(new Action<ClinicCase>(this.ClinicCases_Attach), new Action<ClinicCase>(this.ClinicCases_Detach));
_patientsAddresses = new EntitySet<PatientAddress>(new Action<PatientAddress>(this.PatientsAddresses_Attach), new Action<PatientAddress>(this.PatientsAddresses_Detach));
_patientsPhoneNumbers = new EntitySet<PatientPhoneNumber>(new Action<PatientPhoneNumber>(this.PatientsPhoneNumbers_Attach), new Action<PatientPhoneNumber>(this.PatientsPhoneNumbers_Detach));
this.OnCreated();
}
[Column(Storage="_birthday", Name="Birthday", DbType="integer", AutoSync=AutoSync.Never, CanBeNull=false)]
[DebuggerNonUserCode()]
public long BirthdayBinaryDate
{
get
{
return this._birthday;
}
set
{
if ((_birthday != value))
{
this.OnBirthdayChanging(value);
this.SendPropertyChanging();
this._birthday = value;
this.SendPropertyChanged("Birthday");
this.OnBirthdayChanged();
}
}
}
[Column(Storage="_firstName", Name="FirstName", DbType="text", AutoSync=AutoSync.Never, CanBeNull=false)]
[DebuggerNonUserCode()]
public string FirstName
{
get
{
return this._firstName;
}
set
{
if (((_firstName == value)
== false))
{
this.OnFirstNameChanging(value);
this.SendPropertyChanging();
this._firstName = value;
this.SendPropertyChanged("FirstName");
this.OnFirstNameChanged();
}
}
}
[Column(Storage="_hasChildren", Name="HasChildren", DbType="integer", AutoSync=AutoSync.Never, CanBeNull=false)]
[DebuggerNonUserCode()]
public int HasChildren
{
get
{
return this._hasChildren;
}
set
{
if ((_hasChildren != value))
{
this.OnHasChildrenChanging(value);
this.SendPropertyChanging();
this._hasChildren = value;
this.SendPropertyChanged("HasChildren");
this.OnHasChildrenChanged();
}
}
}
[Column(Storage="_id", Name="ID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.OnInsert)]
[DebuggerNonUserCode()]
public System.Nullable<int> ID
{
get
{
return this._id;
}
set
{
if ((_id != value))
{
this.OnIDChanging(value);
this.SendPropertyChanging();
this._id = value;
this.SendPropertyChanged("ID");
this.OnIDChanged();
}
}
}
[Column(Storage="_isMarried", Name="IsMarried", DbType="integer", AutoSync=AutoSync.Never, CanBeNull=false)]
[DebuggerNonUserCode()]
public int IsMarried
{
get
{
return this._isMarried;
}
set
{
if ((_isMarried != value))
{
this.OnIsMarriedChanging(value);
this.SendPropertyChanging();
this._isMarried = value;
this.SendPropertyChanged("IsMarried");
this.OnIsMarriedChanged();
}
}
}
[Column(Storage="_lastName", Name="LastName", DbType="text", AutoSync=AutoSync.Never, CanBeNull=false)]
[DebuggerNonUserCode()]
public string LastName
{
get
{
return this._lastName;
}
set
{
if (((_lastName == value)
== false))
{
this.OnLastNameChanging(value);
this.SendPropertyChanging();
this._lastName = value;
this.SendPropertyChanged("LastName");
this.OnLastNameChanged();
}
}
}
[Column(Storage="_profession", Name="Profession", DbType="text", AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public string Profession
{
get
{
return this._profession;
}
set
{
if (((_profession == value)
== false))
{
this.OnProfessionChanging(value);
this.SendPropertyChanging();
this._profession = value;
this.SendPropertyChanged("Profession");
this.OnProfessionChanged();
}
}
}
#region Children
[Association(Storage="_clinicCases", OtherKey="PatientID", ThisKey="ID", Name="fk_ClinicCases_0")]
[DebuggerNonUserCode()]
public EntitySet<ClinicCase> ClinicCases
{
get
{
return this._clinicCases;
}
set
{
this._clinicCases = value;
}
}
[Association(Storage="_patientsAddresses", OtherKey="PatientID", ThisKey="ID", Name="fk_PatientsAddresses_0")]
[DebuggerNonUserCode()]
public EntitySet<PatientAddress> Addresses
{
get
{
return this._patientsAddresses;
}
set
{
this._patientsAddresses = value;
}
}
[Association(Storage="_patientsPhoneNumbers", OtherKey="PatientID", ThisKey="ID", Name="fk_PatientsPhoneNumbers_0")]
[DebuggerNonUserCode()]
public EntitySet<PatientPhoneNumber> PhoneNumbers
{
get
{
return this._patientsPhoneNumbers;
}
set
{
this._patientsPhoneNumbers = value;
}
}
#endregion
public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;
if ((h != null))
{
h(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(string propertyName)
{
System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;
if ((h != null))
{
h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
#region Attachment handlers
private void ClinicCases_Attach(ClinicCase entity)
{
this.SendPropertyChanging();
entity.Patient = this;
}
private void ClinicCases_Detach(ClinicCase entity)
{
this.SendPropertyChanging();
entity.Patient = null;
}
private void PatientsAddresses_Attach(PatientAddress entity)
{
this.SendPropertyChanging();
entity.Patient = this;
}
private void PatientsAddresses_Detach(PatientAddress entity)
{
this.SendPropertyChanging();
entity.Patient = null;
}
private void PatientsPhoneNumbers_Attach(PatientPhoneNumber entity)
{
this.SendPropertyChanging();
entity.Patient = this;
}
private void PatientsPhoneNumbers_Detach(PatientPhoneNumber entity)
{
this.SendPropertyChanging();
entity.Patient = null;
}
#endregion
}
[Table(Name="main.PatientsAddresses")]
public partial class PatientAddress : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged
{
private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");
private string _address;
private string _domicileStatus;
private System.Nullable<int> _patientID;
private EntityRef<Patient> _patients = new EntityRef<Patient>();
#region Extensibility Method Declarations
partial void OnCreated();
partial void OnAddressChanged();
partial void OnAddressChanging(string value);
partial void OnDomicileStatusChanged();
partial void OnDomicileStatusChanging(string value);
partial void OnPatientIDChanged();
partial void OnPatientIDChanging(System.Nullable<int> value);
#endregion
public PatientAddress()
{
this.OnCreated();
}
[Column(Storage="_address", Name="Address", DbType="text", IsPrimaryKey=true, AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public string Address
{
get
{
return this._address;
}
set
{
if (((_address == value)
== false))
{
this.OnAddressChanging(value);
this.SendPropertyChanging();
this._address = value;
this.SendPropertyChanged("Address");
this.OnAddressChanged();
}
}
}
[Column(Storage="_domicileStatus", Name="DomicileStatus", DbType="text", AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public string DomicileStatus
{
get
{
return this._domicileStatus;
}
set
{
if (((_domicileStatus == value)
== false))
{
this.OnDomicileStatusChanging(value);
this.SendPropertyChanging();
this._domicileStatus = value;
this.SendPropertyChanged("DomicileStatus");
this.OnDomicileStatusChanged();
}
}
}
[Column(Storage="_patientID", Name="PatientID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public System.Nullable<int> PatientID
{
get
{
return this._patientID;
}
set
{
if ((_patientID != value))
{
if (_patients.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnPatientIDChanging(value);
this.SendPropertyChanging();
this._patientID = value;
this.SendPropertyChanged("PatientID");
this.OnPatientIDChanged();
}
}
}
#region Parents
[Association(Storage="_patients", OtherKey="ID", ThisKey="PatientID", Name="fk_PatientsAddresses_0", IsForeignKey=true)]
[DebuggerNonUserCode()]
public Patient Patient
{
get
{
return this._patients.Entity;
}
set
{
if (((this._patients.Entity == value)
== false))
{
if ((this._patients.Entity != null))
{
Patient previousPatients = this._patients.Entity;
this._patients.Entity = null;
previousPatients.Addresses.Remove(this);
}
this._patients.Entity = value;
if ((value != null))
{
value.Addresses.Add(this);
_patientID = value.ID;
}
else
{
_patientID = null;
}
}
}
}
#endregion
public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;
if ((h != null))
{
h(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(string propertyName)
{
System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;
if ((h != null))
{
h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
I use the following code to add an address to a patient:
PatientAddress address = new PatientAddress();
address.Address = txtAddress.Text;
address.DomicileStatus = cmbDomicileStatus.Text;
currentPatient.Addresses.Add(address);
Database.Source.PatientsAddresses.InsertOnSubmit(address);
Database.Source.SubmitChanges();
Database.Source is an instance of the class that extends DataContext in the generated code. On SubmitChanges, I receive this exception:
"Equal operator is not defined between Nullable(Of Int32) and Int32."
The message is not reported word by word, but the meaning is the same. The stack trace point to DbLinq code, more precisely to line 709 of source file DbLinq.Data.Linq.DataContext.cs. You can find the source files here: http://dblinq.codeplex.com/SourceControl/changeset/view/16800#314775 (under the body of the method SetEntityRefQueries(object entity)).
I see that the problem comes when comparing a foreign key value with a constant in an expression tree, but I couln't manage to get other information on that. Can you help me find the issue?
N.B.: the field address.PatientID (foreign key) is actually set to the correct value before the invocation of SubmitChanges.
As I mentioned in the comment above (which I'm repeating here so I can link images), your primary key should not be nullable. There should be a property in your mapping that you can change to set it, although I don't use DbLinq, so I can't give you a screenshot of it directly. Instead, here it is in the LINQ-2-SQL DBML designer (left) and the Entity Framework EDMX designer (right).
I'm not as sure about your deletion problem - that seems like it should work to me. Can you edit your question to include the whole block of your deletion code? As a preliminary guess, you're either creating a new object (instead of loading one) and then trying to delete it, or you're deleting the association without deleting the object.
As a general rule, I never delete from a database when I can avoid it - I just mark inactive. It's much easier to "undelete" that way.
Did you try: address.Patient = currentPatient
instead of: currentPatient.Addresses.Add(address)?
PatientAddress address = new PatientAddress();
address.Address = txtAddress.Text;
address.DomicileStatus = cmbDomicileStatus.Text;
address.Patient = currentPatient;
Database.Source.PatientsAddresses.InsertOnSubmit(address);
Database.Source.SubmitChanges();

Categories