Storing arbitrary complex objects in c# to database [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am currently programming to multiple API's. Till now I have created classes that use EF syntax (id = classNameId etc...) and convert whatever item is being returned to EF object. Since I'm using the C# Wrappers (created by whatever company created the API) for the API's I can't simply alter whatever class it is that I want to store to the database to use EF Syntax. Is there any project that would allow me to dynamically generate tables and columns for any generic object using run time reflection?
Keep in mind that many of the complex objects have within them complex objects.
As of right now I'm considering writing a script to generate inherited classes for each of the Complex Types (identified via reflection) and inserting a Id (and whetever other information EF would need to generate DB) into the inherited class. This would get a little complicated as it would require implicit conversions for Ienumerable to Ienumerable.
Any help would be greatly appreciated.
Thank You.

What you actually need is some schema-less database, like MongoDB or RavenDb instead of relational. These allows to do exactly what you said in the title: to store arbitraty complex objects in db.

You may want to look at OrmLite and see if it meets your reqs.
public class SimpleExample
{
public int Id { get; set; }
public string Name { get; set; }
}
//Set once before use (i.e. in a static constructor).
OrmLiteConfig.DialectProvider = new SqliteOrmLiteDialectProvider();
using (IDbConnection db = "/path/to/db.sqlite".OpenDbConnection())
using (IDbCommand dbConn = db.CreateCommand())
{
dbConn.CreateTable<SimpleExample>(true);
dbConn.Insert(new SimpleExample { Id=1, Name="Hello, World!"});
var rows = dbConn.Select<SimpleExample>();
Assert.That(rows, Has.Count(1));
Assert.That(rows[0].Id, Is.EqualTo(1));
}

Related

Changing an Existing class - Best Practice Open/Closed Principle [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I am trying to figure out the best way to change an existing class.
So the class is called ExcelReport and it has one method Create(data,headings). This is live and used in many places. Now recently I want to change the method so I can format columns in Excel.
Create(data, headings, columnformats)
So as not to upset my existing programs the best I can come up with is to add another method Create2(data,headings,columnformats) to the class.
I got a lot of suggestions saying I should modify the existing class with a overloaded method, which I did. But does this not break the Open/Close Principle as my existing class was in production?
Should I have created a new class ExcelReport2(and Interface) with the new improved method and passed this into my new program using dependency injection?
OCP
In object-oriented programming, the open–closed principle states "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification";[1] that is, such an entity can allow its behaviour to be extended without modifying its source code.
Your solution
You will most likely want to create more options later on for this.
And since you asked for an open/closed principle answer we need to take that into account (open for extension, closed for change).
A more robust alternative is to create a new overload:
void Create(CreationOptions options);
Looks trivial, right? The thing is that any subclass can introduce their own options like MyPinkThemedFormattedCellsCreationOptions.
So your new option class would look like this as of now:
public class CreationOptions
{
public SomeType Data { get; set; }
public SomeType Headings { get; set; }
public SomeType[] ColumnFormats { get; set; }
}
That's open for extension and closed for change as new features doesn't touch the existing API, since now you only have to create sub classes based on CreationOptions for new features.

How do you store C# Property in SQL Server database and invoke command? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I would assume it wouldn't be complicated to do the following:
I have a VARCHAR database field that will store a C# property such as "DateTime.Now.Year". I want to pass this value into my ASP.NET application and dynamically return 2017.
How do I read the VARCHAR value as a string and get the C# method to invoke the property?
You could achieve this using System.Reflection, but you really need to store information about the assembly, class and property/field/method you want to invoke.
for example if you stored:
AssemblyPath: "c:\something\someassembly.dll"
ClassFullPath: "SomeAssembly.SomeNameSpace.SomeClass, SomeClass"
MethodName: "someMethodName"
Then in your code you could attempt to load the assembly and instantiate the class:
var assembly = Assembly.Load(assemblyPath);
var clss = Activator.CreateInstance(ClassFullPath);
var method = clss.GetType().GetMethod(MethodName);
var result = method.Invoke();
Now that is a super simplified example, and there are many things to consider like access to the method / property / field etc. (i.e. private vs public .. and static vs instance)
So if you can really reduce your cases and design a set of flags / options you can store in your table, it will be possible.

Not exposing IQueryable and not violating OC principle [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I was reading about the repository pattern the last few days and everyone talking about it do not expose IQueryable from repository like this (like here and here):
public interface ICustomersRepository
{
IQueryable<Customer> Customers{ get; }
}
And it is accepted by large amount of developers to avoid this.
But when it comes to filtering large amount of data and custom filters from UI (like a report with over 10 filter options for searching in data over 1 million records) is IQueryable?
Especially when there is a framework and other low-level developers are using the repository for developing custom reports. They can not always use GetAll for this purpose.
So as mentioned in other threads like this or this, I should have methods for each one of the reports that I have in my repositories, and they should return IEnumerable. Here is what is not clear to me:
If I have a new report I have to change my repository for that and add a new method. And if I change my repository I've violated the Open/Close principle.
Here is my problem: I don't want to expose Iqueryable and on the other hand, I don't want to change my repository for every report.
A repository is an abstraction over your Data Access Layer (DAL). In Java, they are also known as DAOs (Data Access Objects). So, exposing IQueryable<T> in a repository is bad practice because of this reason, you are tying LINQ queries to the client code.
So, to fix it you should create an object which would follow the command pattern with all the filtering options you support. Then return a List<T> or any sorted collection you want to use (maybe IList<T> is more appropriate).
An example
class BookFilter
{
public string NameStartsWith { get; set; }
public string ISBN { get; set; }
public DateTime PublishedAfter { get; set; }
// ....
}
public interface IBookRepository
{
IList<Book> Filter(BookFilter filter);
}

Class Name: Append DTO or Entity [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Is there any preference on either appending DTO or Entity to a class name?
Is there any standard around this?
1 Class is used by ORM (EntityFramework) and the other class is used for serialization.
The reason for this is so that there is no duplication of all fields as the EntityFramework is a wrapper around the DTO class(most but not all properties).
The DTO class is in a shared library, and decoupled from EF.
E.g. Which of these is the most common/standard approach?
// 1.
MyNamespace.Entities.MyClass
MyNamespace.Models .MyClassDto
// 2.
MyNamespace.Entities.MyClassEntity
MyNamespace.Models .MyClass
// 3.
MyNamespace.Entities.MyClassEntity
MyNamespace.Models .MyClassDto
In my personal experience your third example is the only implementation I have worked with and it is the one I would argue for because the intent of the object you are working with will always be clear whereas with the other two it only becomes clear when looking at both objects together.
That being said as long as your team comes to an agreement on which to use any would work.
In my opinion, you typically don't want to put implementation details into class names for similar reasons to why you don't want to use Hungarian Notation.
If there's a bit of code that needs to work with both types and differentiate between them, another option is including aliased using statements like this:
using entities = MyNamespace.Entities;
using dto = MyNamespace.Models;
//in code
var myClassEntity = new entities.MyClass();
var myClassDto = new dto.MyClass();
//work with both
My assumption is that the code that needs to work with both types is limited to an isolated library, and that client code typically works with one, not both types.

OOP interaction with database [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
If object oriented programming is focused on objects, which consist of methods and data, what is the best OOP-focused approach to working with databases, using C#?
For example, I want to log something using C# classes, and record the logs in a SQL table. All other factors being neutral, would it be more "proper," object-oriented speaking, to do:
Create a class for what's being logged, and include methods for database access
(The methods are tied closely to data)
public class Activity
{
public string ActivityProperty { get; set; }
public void SQLMethod1() {}
public void SQLMethod2() {}
}
...or,
Create a class for what's being logged, and create a class for database access
(Methods are not closely tied to data, but the way data is accessed is treated itself as an object, i.e. referencing EF or another ORM)
public class Activity
{
public string ActivityProperty { get; set; }
}
public class SQLMethods
{
public string SQLProperty { get; set; }
public void SQLMethod1(Activity activityParam) { }
public void SQLMethod2(Activity activityParam) { }
}
...or, perhaps a better design would be more "object-oriented"?
Generally speaking, I prefer not to put database access logic into classes because it hinders your ability to use them in other scenarios in which data access is not required. So I think your second option is the more flexible one.
However, if you are already aware of ORM solutions such as Entity Framework, I would suggest using one of those. EF takes an approach closer to your second one in which you use POCOs (plain old C# classes) and other EF classes take care of moving data from those objects into the database and back.
So overall my suggestion would be to use Entity Framework with the code first methodology.

Categories