For example, say we have a ticketing system that can be configured to offer tickets at normal price, but once you're within X hours of the event, you offer them at a different price (it may be discounted or increased). We'll call this the 'rush price'. Moreover, once you're within Y hours of the event, you offer them at yet another price. We'll call this the 'emergency price'.
The class that represents this configuration information might look like this:
public class RushTicketPolicy {
private int rushHours;
private int emergencyHours;
public RushTicketPolicy(int rushHours, int emergencyHours) {
this.rushHours = rushHours;
this.emergencyHours = emergencyHours;
}
public int RushHours { get { return this.rushHours; } }
public int EmergencyHours { get { return this.emergencyHours; } }
}
I'm finding it extremely difficult to come up with names for these variables (and properties) that are sufficiently expressive and complete, without reference to the code that uses them and without additional inference.
That is, someone that hasn't seen the rest of the code or know anything about its business requirements should be able to look at the variable names and understand that:
Rush sales start X hours before the event, inclusive.
Emergency sales start Y hours before the event, inclusive.
What are some names that would accomplish that?
public class SalesPeriodStartRule {
private int mHoursBeforeEvent = 0;
public SalesPeriodStartRule(int hoursBeforeEvent) {
mHours = hoursBeforeEvent;
}
public DateTime GetEffectiveDate(DateTime showDate) {
return showDate.AddHours(-mHoursBeforeEvent);
}
}
public class PricingPolicy {
private SalesPeriodStartRule mRushRule;
private SalesPeriodStartRule mEmergencyRule;
public PricingPolicy(SalesPeriodStartRule rushRule, SalesPeriodStartRule emergencyRule) {
mRushRule = rushRule;
mEmergencyRule = emergencyRule;
}
public string GetPriceCategory(DateTime purchaseDate, DateTime showDate) {
if (purchaseDate > mEmergencyRule.GetEffectiveDate(showDate)) {
return "Emergency";
}
else if (purchaseDate > mRushRule.GetEffectiveDate(showDate)) {
return "Rush";
}
else {
return "Standard";
}
}
}
I'm a fan of verbosity here:
DiscountThresholdInSeconds
Based on your edit #1:
If you have a class "Ticket," I would simply give it a collection of discounts:
public class Ticket
{
private List <Discount> m_availableDiscounts = new List<Discount>();
private decimal m_basePrice = 0m;
private DateTime m_showTime;
public Ticket(DateTime showTime)
{
m_showTime = showTime;
}
public List<Discount> Discounts
{
get
{
return m_availableDiscounts;
}
}
public decimal BasePrice
{
get
{
return m_basePrice;
}
set
{
m_basePrice = value;
}
}
public DateTime ShowTime
{
get
{
return m_showTime;
}
}
public decimal CalculatePrice(int quantity)
{
//Apply discounts here...
}
}
public class Discount
{
private int m_thresholdInSeconds = 0;
private decimal m_percentOff = 0m;
private decimal m_flatAmountOff = 0m;
public Discount(int thresholdInSeconds, decimal percentOff, decimal flatAmountOff)
{
m_thresholdInSeconds = thresholdInSeconds;
m_percentOff = percentOff;
m_flatAmountOff = flatAmountOff;
}
public int ThresholdInSeconds
{
get
{
return m_thresholdInSeconds;
}
}
public decimal PercentOff
{
get
{
return m_percentOff;
}
}
public decimal FlatAmountOff
{
get
{
return m_flatAmountOff;
}
}
}
Edit #2 based on question Edit #2
The difference between what you have listed and the code I provided is that yours only allows for two distinct discount periods while mine will support the tiered model. If we really are talking about tickets here, think about it like a timeline:
Now-------------------------------------------------------------------------ShowTime
At any time in that period, you may have surpassed a threshold (checkpoint, boundary, whatever) that qualifies you for a discount.
------------|------Now------------|------------------|---------------|---|---ShowTime
Since ShowTime is the stable piece of information in this time line, you need to capture "distance" from showtime and the applicable discount. The "distance" from ShowTime is the threshold that gets crossed.
Name it what it represents ... :D
RushTicketPolicyValidityIntervalLength
Okay, the class has already part of the information. So what about this?
ValidityIntervalLength
Or something similar.
Perhaps you could use a fluent interface to make the API a bit more expressive.
Consider the following:
public class Test
{
public string TestPolicies()
{
int year = 2010;
int month = 11;
int day = 3;
int hour = 15;
int minute = 30;
int second = 0;
DateTime eventDateTime = new DateTime(year, month, day, hour, minute, second);
IConfiguredTicketPolicy emergencyTicketPolicy = new TicketPolicy().Starts(2).HoursBefore(eventDateTime).Inclusive();
IConfiguredTicketPolicy rushTicketPolicy = new TicketPolicy().Starts(4).HoursBefore(eventDateTime).Inclusive();
DateTime now = DateTime.Now;
if (emergencyTicketPolicy.IsEffectiveAsOf(now))
{
return "Emergency";
}
else if (rushTicketPolicy.IsEffectiveAsOf(now))
{
return "Rush";
}
else
{
return "Standard";
}
}
}
What an implementation of the TicketPolicy class that looks something like this:
public class TicketPolicy : IConfigurePolicySalesStart, IConfigurePolicyHoursBefore, IConfigurePolicyInclusive, IConfiguredTicketPolicy
{
private int mHours;
public IConfigurePolicyHoursBefore Starts(int hours)
{
TicketPolicy clone = this.Clone();
clone.mHours = hours;
return clone;
}
private DateTime mEventDateTime;
public IConfigurePolicyInclusive HoursBefore(DateTime eventDateTime)
{
TicketPolicy clone = this.Clone();
clone.mEventDateTime = eventDateTime;
return clone;
}
private bool mInclusive = false;
public IConfiguredTicketPolicy Inclusive()
{
TicketPolicy clone = this.Clone();
clone.mInclusive = true;
return clone;
}
public bool IsEffectiveAsOf(DateTime now)
{
DateTime effectiveDate = mEventDateTime.AddHours(-1*this.mHours);
if (!this.mInclusive)
{
effectiveDate = effectiveDate.AddTicks(1);
}
return effectiveDate.CompareTo(now) < 0;
}
public TicketPolicy Clone()
{
TicketPolicy clone = new TicketPolicy();
clone.Starts(this.mHours);
clone.HoursBefore(this.mEventDateTime);
if (this.mInclusive)
{
clone.Inclusive();
}
return clone;
}
}
The interfaces are used to help intellisense navigate the user through the API and may not be necessary. They might look something like this:
public interface IConfigurePolicySalesStart
{
IConfigurePolicyHoursBefore Starts(int hours);
}
public interface IConfigurePolicyHoursBefore
{
IConfigurePolicyInclusive HoursBefore(DateTime eventDateTime);
}
public interface IConfigurePolicyInclusive
{
IConfiguredTicketPolicy Inclusive();
}
public interface IConfiguredTicketPolicy
{
bool IsEffectiveAsOf(DateTime now);
}
Related
I just started to use Dapper. Dapper works fine. As a next step when I tried to integrate with Dapper Extension. It generates an exception called System.Data.OleDb.OleDbException "Additional information: Characters found after end of SQL statement." Why is that? Dapper Extension doesn't support Ms Access (because of the end character) or problem with my code or I am missing something. My code is below
using (var conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=myAccessFile.accdb;"))
{
conn.Open();
conn.Insert<Person>(new Person { Name = "John Stan", Age = 20 });
}
According to an MSDN article,
Some database engines, such as the Microsoft Access Jet database engine, do not support output parameters and cannot process multiple statements in a single batch.
So the problem is that the Insert method is generating a statement such as
INSERT INTO [Person] ([Person].[PersonName]) VALUES (#PersonName);
SELECT CAST(SCOPE_IDENTITY() AS BIGINT) AS [Id]
and Access can't deal with it.
Reading around, it seems like that are various suggestions as to how to do insert-and-get-new-record-key when dealing with Access (that MSDN article suggests a second SELECT statement) but that doesn't help if you're using the DapperExtensions library, since that is what generates the query for you.
So, basically, I think that you are correct in thinking that DapperExtensions won't work with Access.
On a side note, I had a nightmare trying to find out what queries were being generated. There are various articles that talk about a registry hack to set a "JETSHOWPLAN" value to "ON" but I couldn't make any of them work. In the end, I created wrapped database connection and command classes so that the queries could be captured on the way out. In case this is of any use to anyone in the future, I'm including it below..
The database connection initialisation code needs to change slightly - eg.
var connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Database2.mdb;";
using (var conn = new WrappedDbConnection(new OleDbConnection(connectionString)))
{
conn.Insert<Person>(new Person { PersonName = "Dan" });
}
and the following two classes need to be defined -
public class WrappedDbConnection : IDbConnection
{
private readonly IDbConnection _conn;
public WrappedDbConnection(IDbConnection connection)
{
if (connection == null)
throw new ArgumentNullException(nameof(connection));
_conn = connection;
}
public string ConnectionString
{
get { return _conn.ConnectionString; }
set { _conn.ConnectionString = value; }
}
public int ConnectionTimeout
{
get { return _conn.ConnectionTimeout; }
}
public string Database
{
get { return _conn.Database; }
}
public ConnectionState State
{
get { return _conn.State; }
}
public IDbTransaction BeginTransaction()
{
return _conn.BeginTransaction();
}
public IDbTransaction BeginTransaction(IsolationLevel il)
{
return _conn.BeginTransaction(il);
}
public void ChangeDatabase(string databaseName)
{
_conn.ChangeDatabase(databaseName);
}
public void Close()
{
_conn.Close();
}
public IDbCommand CreateCommand()
{
return new WrappedDbCommand(_conn.CreateCommand());
}
public void Dispose()
{
_conn.Dispose();
}
public void Open()
{
_conn.Open();
}
}
public class WrappedDbCommand : IDbCommand
{
private readonly IDbCommand _cmd;
public WrappedDbCommand(IDbCommand command)
{
if (command == null)
throw new ArgumentNullException(nameof(command));
_cmd = command;
}
public string CommandText
{
get { return _cmd.CommandText; }
set { _cmd.CommandText = value; }
}
public int CommandTimeout
{
get { return _cmd.CommandTimeout; }
set { _cmd.CommandTimeout = value; }
}
public CommandType CommandType
{
get { return _cmd.CommandType; }
set { _cmd.CommandType = value; }
}
public IDbConnection Connection
{
get { return _cmd.Connection; }
set { _cmd.Connection = value; }
}
public IDataParameterCollection Parameters
{
get { return _cmd.Parameters; }
}
public IDbTransaction Transaction
{
get { return _cmd.Transaction; }
set { _cmd.Transaction = value; }
}
public UpdateRowSource UpdatedRowSource
{
get { return _cmd.UpdatedRowSource; }
set { _cmd.UpdatedRowSource = value; }
}
public void Cancel()
{
_cmd.Cancel();
}
public IDbDataParameter CreateParameter()
{
return _cmd.CreateParameter();
}
public void Dispose()
{
_cmd.Dispose();
}
public int ExecuteNonQuery()
{
Console.WriteLine($"[ExecuteNonQuery] {_cmd.CommandText}");
return _cmd.ExecuteNonQuery();
}
public IDataReader ExecuteReader()
{
Console.WriteLine($"[ExecuteReader] {_cmd.CommandText}");
return _cmd.ExecuteReader();
}
public IDataReader ExecuteReader(CommandBehavior behavior)
{
Console.WriteLine($"[ExecuteReader({behavior})] {_cmd.CommandText}");
return _cmd.ExecuteReader();
}
public object ExecuteScalar()
{
Console.WriteLine($"[ExecuteScalar] {_cmd.CommandText}");
return _cmd.ExecuteScalar();
}
public void Prepare()
{
_cmd.Prepare();
}
}
Now, the queries are written to the console before being sent to the database.
We have a C# Windows Phone application and I am trying to make use of dbschemaupdater.AddIndex().
However, I am unsure of how to define the fields associated with the index and cannot find any online examples that seem relevant.
Our database tables are defined as classes via SQLMetal, e.g.
[global::System.Data.Linq.Mapping.TableAttribute(Name = "PDA_AppActiveLog")]
public partial class PDA_AppActiveLog : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
[Column(IsVersion = true)]
private Binary version;
private int _AppActiveLogID;
private DateTime _EventTime;
private string _EventCode;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnAppActiveLogIDChanging(int value);
partial void OnAppActiveLogIDChanged();
partial void OnEventTimeChanging(DateTime value);
partial void OnEventTimeChanged();
partial void OnEventCodeChanging(string value);
partial void OnEventCodeChanged();
#endregion
public PDA_AppActiveLog()
{
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_AppActiveLogID", AutoSync = AutoSync.OnInsert, DbType = "Int NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true)]
public int AppActiveLogID
{
get
{
return this._AppActiveLogID;
}
set
{
if ((this._AppActiveLogID != value))
{
this.OnAppActiveLogIDChanging(value);
this.SendPropertyChanging();
this._AppActiveLogID = value;
this.SendPropertyChanged("AppActiveLogID");
this.OnAppActiveLogIDChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_EventTime", DbType = "DateTime NOT NULL", CanBeNull = false)]
public DateTime EventTime
{
get
{
return this._EventTime;
}
set
{
if ((this._EventTime != value))
{
this.OnEventTimeChanging(value);
this.SendPropertyChanging();
this._EventTime = value;
this.SendPropertyChanged("EventTime");
this.OnEventTimeChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_EventCode", DbType = "NVarChar(30)", UpdateCheck = UpdateCheck.Never, CanBeNull = true)]
public string EventCode
{
get
{
return this._EventCode;
}
set
{
if ((this._EventCode != value))
{
this.OnEventCodeChanging(value);
this.SendPropertyChanging();
this._EventCode = value;
this.SendPropertyChanged("EventCode");
this.OnEventCodeChanged();
}
}
}
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));
}
}
}
Within our code, we add something like:
if (dbSchema.DatabaseSchemaVersion == 8)
{
dbSchema.AddTable<PDA_AppActiveLog>();
dbSchema.DatabaseSchemaVersion = 9;
//dbSchema.AddIndex<PDA_AppActiveLog>("EventCode");
dbSchema.Execute();
dbSchema = dc.CreateDatabaseSchemaUpdater();
}
However, I am unsure how to define which fields belong to the new index.
It seems from this article, that the functionality is there:
http://justinangel.net/AllWp7MangoAPIs#linq2sql
However, all the examples I've seen show the database definition code differently, e.g.:
http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394022(v=vs.105).aspx#BKMK_Preparingversion3Addinganindexconsideringmultipleupgradepaths
// Index added in version 3 of the application.
[Index(Columns = "Priority", Name = "PriorityIndex")]
I am unsure if I can make equivalent changes, but even if I am, then I can no longer use SQLMetal to pre-generate the classes unless I want to modify them everytime afterwards?
What is the best way to get an index added?
Thanks.
I have three MvxSpinners in my android view.
These spinners are binded to three different lists.
and Mode of data binding is TwoWay for these spinners.i.e. when this view is
displayed,all of these three spinners are get displayed with the predefined values.
When user change the value in first spinner,then second spinner will be clear and
get loaded with new values based on the selected value in first spinner.
How can I achieve this?
There's many ways to accomplish this, where the code placement is really up to you. Overall the idea would be to have a "SelectedItem" object that you can pass into your method and "Load" the next List.
Please keep in mind that this code is more traditional MVVM, but can easily be converted to MVVMCross equivalent. I believe all these types should be supported by MVVMCross.
private MyFirstObject _selectedFirstObject;
public MyFirstObject SelectedFirstObject
{
get { return _selectedFirstObject; }
set
{
_selectedFirstObject = value;
RaisePropertyChanged("SelectedFirstObject");
if(value != null)
LoadMySecondObjects(value);
}
}
private ObservableCollection<MyFirstObject> _myFirstObjects;
public ObservableCollection<MyFirstObject> MyFirstObjects
{
get { return _myFirstObjects; }
set
{
_myFirstObjects = value;
RaisePropertyChanged("MyFirstObjects");
}
}
private ObservableCollection<MySecondObject> _mySecondObjects;
public ObservableCollection<MySecondObject> MySecondObjects
{
get { return _mySecondObjects; }
set
{
_mySecondObjects = value;
RaisePropertyChanged("MySecondObjects");
}
}
public void LoadMySecondObjects(MyFirstObject current)
{
//Wherever you're pulling data from
MySecondObjects = MyDataService.GetAll(current);
}
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
I had the same problem but only if you add null value (as a default value) to your ItemsSource and try to reset SelectedItem to null. SelectedItem is changed in ViewModel but not in the spinner. In that case there's number of solutions but I used message to inform View to set selected item
public class SpinnerSelectionChanged : MvxMessage
{
public SpinnerSelectionChanged(object sender, string spinnerName, int position): base(sender)
{
SpinnerName = spinnerName;
Position = position;
}
public string SpinnerName { get; set; }
public int Position { get; set; }
}
in View
private void OnSpinnerSelectionChanged(SpinnerSelectionChanged obj)
{
switch (obj.SpinnerName)
{
case "City":
_spinnerCity.SetSelection(obj.Position);
break;
case "Office":
_spinnerOffice.SetSelection(obj.Position);
break;
}
}
I am working on upgrading our project from .Net 2 to .Net4.5, at the same time I'm pushing as many references as I can to NuGet and making sure the versions are current.
I am having a problem getting one of the tests to run
The Test Classes:
public class Person
{
public static int PersonBaseMethodHitCount { get; set; }
public virtual void BaseMethod()
{
PersonBaseMethodHitCount = PersonBaseMethodHitCount + 1;
}
public static int PersonSomeMethodToBeOverriddenHitCount { get; set; }
public virtual void SomeMethodToBeOverridden()
{
PersonSomeMethodToBeOverriddenHitCount = PersonSomeMethodToBeOverriddenHitCount + 1;
}
}
public class Employee : Person
{
public static int EmployeeSomeMethodToBeOverriddenHitCount { get; set; }
public override void SomeMethodToBeOverridden()
{
EmployeeSomeMethodToBeOverriddenHitCount = EmployeeSomeMethodToBeOverriddenHitCount + 1;
}
public static int EmployeeCannotInterceptHitCount { get; set; }
public void CannotIntercept()
{
EmployeeCannotInterceptHitCount = EmployeeCannotInterceptHitCount + 1;
}
public virtual void MethodWithParameter(
[SuppressMessage("a", "b"), InheritedAttribute, Noninherited]string foo)
{
}
}
public class MyInterceptor : IInterceptor
{
public static int HitCount { get; set; }
public void Intercept(IInvocation invocation)
{
HitCount = HitCount + 1;
invocation.Proceed();
}
}
The test (there is no setup for this fixture):
var container = new WindsorContainer();
container.Register(Component.For<MyInterceptor>().ImplementedBy<MyInterceptor>());
container.Register(
Component
.For<Employee>()
.ImplementedBy<Employee>()
.Interceptors(InterceptorReference.ForType<MyInterceptor>())
.SelectedWith(new DerivedClassMethodsInterceptorSelector()).Anywhere);
container.Register(Classes.FromAssembly(Assembly.GetExecutingAssembly()).Pick().WithService.FirstInterface());
var employee = container.Resolve<Employee>();
Person.PersonBaseMethodHitCount = 0;
Person.PersonSomeMethodToBeOverriddenHitCount = 0;
Employee.EmployeeCannotInterceptHitCount = 0;
Employee.EmployeeSomeMethodToBeOverriddenHitCount = 0;
MyInterceptor.HitCount = 0;
employee.BaseMethod();
Assert.That(Person.PersonBaseMethodHitCount, Is.EqualTo(1));
// The BaseMethod was not overridden in the derived class so the interceptor should not have been called.
Assert.That(MyInterceptor.HitCount, Is.EqualTo(0));
Person.PersonBaseMethodHitCount = 0;
Person.PersonSomeMethodToBeOverriddenHitCount = 0;
Employee.EmployeeCannotInterceptHitCount = 0;
Employee.EmployeeSomeMethodToBeOverriddenHitCount = 0;
MyInterceptor.HitCount = 0;
employee.SomeMethodToBeOverridden();
Assert.That(Person.PersonSomeMethodToBeOverriddenHitCount, Is.EqualTo(0));
Assert.That(Employee.EmployeeSomeMethodToBeOverriddenHitCount, Is.EqualTo(1));
Assert.That(MyInterceptor.HitCount, Is.EqualTo(1)); //The test errors out on this line
Person.PersonBaseMethodHitCount = 0;
Person.PersonSomeMethodToBeOverriddenHitCount = 0;
Employee.EmployeeCannotInterceptHitCount = 0;
Employee.EmployeeSomeMethodToBeOverriddenHitCount = 0;
MyInterceptor.HitCount = 0;
employee.CannotIntercept();
Assert.That(Employee.EmployeeCannotInterceptHitCount, Is.EqualTo(1));
Assert.That(MyInterceptor.HitCount, Is.EqualTo(0));
I added a comment to denote where the test fails.
So far as I can tell the problem is arising in the DerivedClassMethodsInterceptorSelector
Selector:
public class DerivedClassMethodsInterceptorSelector : IInterceptorSelector
{
public IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors)
{
return method.DeclaringType != type ? new IInterceptor[0] : interceptors;
}
}
When it makes the comparison of types, the type variable is System.RuntimeType but should be Employee (at least this is my understanding).
EDIT:
This problem was occurring using Castle.Windsor and Castle.Core 3.2.1, After making NuGet install the 3.1.0 package the code works as expected.
I am leaning towards this being a bug, but I could also just be a change in the logic.
I was able to reproduce the same issue with version 3.3.3 with this simple unit test:
[TestClass]
public class MyUnitTest
{
[TestMethod]
public void BasicCase()
{
var ProxyFactory = new ProxyGenerator();
var aopFilters = new IInterceptor[] {new TracingInterceptor()};
var ConcreteType = typeof(MyChild);
var options = new ProxyGenerationOptions { Selector = new AopSelector() };
var proxy = ProxyFactory.CreateClassProxy(ConcreteType, options, aopFilters) as MyChild;
proxy.DoIt();
}
}
public class AopSelector : IInterceptorSelector
{
public IInterceptor[] SelectInterceptors(Type runtimeType, MethodInfo method, IInterceptor[] interceptors)
{
Assert.IsTrue(runtimeType == typeof(MyChild));
return interceptors;
}
}
public class MyWay
{
public virtual void DoIt()
{
Thread.Sleep(200);
}
}
public class MyChild : MyWay
{
public virtual void DoIt2()
{
Thread.Sleep(200);
}
}
public class TracingInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
var isProperty = invocation.Method.Name.StartsWith("get_")
|| invocation.Method.Name.StartsWith("set_");
if (isProperty)
{
invocation.Proceed();
return;
}
LogMethod(invocation);
}
protected virtual void LogMethod(IInvocation invocation)
{
var target = (invocation.InvocationTarget ?? invocation.Proxy).GetType().Name;
var stopwatch = Stopwatch.StartNew();
try
{
stopwatch.Start();
invocation.Proceed();
}
finally
{
stopwatch.Stop();
var result = stopwatch.ElapsedMilliseconds;
}
}
}
I fixed it by changing Castle's source code and editing method TypeUtil.GetTypeOrNull to look like this:
public static Type GetTypeOrNull(object target)
{
if (target == null)
{
return null;
}
var type = target as Type;
if (type != null)
{
return type;
}
return target.GetType();
}
Of course this is a naive fix, because the problem is somewhere else and it is that instead of an object instance passed to this method, its Type is passed in. However checking if the passed parameter is of type Type and if so returning it instead of calling GetType on it makes it work.
Is it possible to extend LINQ-to-SQL entity-classes with constructor-methods and in the same go; make that entity-class inherit from it's data-context class?--In essence converting the entity-class into a business object.
This is the pattern I am currently using:
namespace Xxx
{
public class User : Xxx.DataContext
{
public enum SiteAccessRights
{
NotRegistered = 0,
Registered = 1,
Administrator = 3
}
private Xxx.Entities.User _user;
public Int32 ID
{
get
{
return this._user.UsersID;
}
}
public Xxx.User.SiteAccessRights AccessRights
{
get
{
return (Xxx.User.SiteAccessRights)this._user.UsersAccessRights;
}
set
{
this._user.UsersAccessRights = (Int32)value;
}
}
public String Alias
{
get
{
return this._user.UsersAlias;
}
set
{
this._user.UsersAlias = value;
}
}
public User(Int32 userID)
{
var user = (from u in base.Users
where u.UsersID == userID
select u).FirstOrDefault();
if (user != null)
{
this._user = user;
}
else
{
this._user = new Xxx.Entities.User();
base.Users.InsertOnSubmit(this._user);
}
}
public User(Xxx.User.SiteAccessRights accessRights, String alias)
{
var user = (from u in base.Users
where u.UsersAccessRights == (Int32)accessRights && u.UsersAlias == alias
select u).FirstOrDefault();
if (user != null)
{
this._user = user;
}
else
{
this._user = new Xxx.Entities.User
{
UsersAccessRights = (Int32)accessRights,
UsersAlias = alias
};
base.Users.InsertOnSubmit(this._user);
}
}
public void DeleteOnSubmit()
{
base.Users.DeleteOnSubmit(this._user);
}
}
}
Update:
Notice that I have two constructor-methods in my User class. I'd like to transfer those to the User entity-class and extend the User entity-class on it's data-context class, so that the data-context is available to the entity-class on "new-up".
Hope this makes sense.
Rick Strahl has a number of really good articles that address what I think you are looking for. Check out his list of Linq Articles Here
Inheriting an entity from a data context is a bad idea. They are two discrete objects and are designed to operate that way. Doing this will cause all sorts of issues least of all problems with trying to submit a bunch of related changes together at the same time - going through multiple data contexts will cause this to fail as each tries to work independently.
It doesn't seem to make sense to make an entity a type of DataContext. It doesn't need to be a DataContext in order to be considered a business object, nor do you necessarily need to create a type that contains the original entity. It might be better to just extend the entity class and contain a reference to a DataContext using composition:
namespace Xxx.Entities
{
public partial class User : IDisposable
{ DataContext ctx;
public static GetUserByID(int userID)
{ var ctx = new DataContext();
var user = ctx.Users.FirstOrDefault(u=>u.UsersID == userID);
if (user == null)
{
user = new User();
ctx.Users.InsertOnSubmit(user);
}
user.ctx = ctx;
return user;
}
public void Dispose() { if (ctx != null) ctx.Dispose(); }
}
}
If you just want the property names to be different than the database column names, do that in the mapping file.