How to map a bit field to boolean property in RepoDB?
How to map a bit column to boolean property in RepoDB?
FluentMapper.Entity<ObjectClass>()
.Table("CLASSES")
.Primary(e => e.Id)
.Column(e => e.Id, "id")
.Column(e => e.Code, "code")
.Column(e => e.IsFrozen, "isfrozen");
//.DbType(e => e.IsFrozen, System.Data.DbType.Boolean);
The property (I tried also using bool?
):
public bool IsFrozen { get; set; } = false;
I got the error:
No coercion operator is defined between types 'System.Decimal' and 'System.Boolean'.
Database values: 0, 1
do you know?
how many words do you know
See also questions close to this topic
-
C# - Adding condition to func results in stack overflow exception
I have a func as part of specification class which sorts the given iqueryable
Func<IQueryable<T>, IOrderedQueryable<T>>? Sort { get; set; }
When i add more than one condition to the func like below , it results in stack overflow exception.
spec.OrderBy(sc => sc.Case.EndTime).OrderBy(sc => sc.Case.StartTime);
The OrderBy method is implemented like this
public ISpecification<T> OrderBy<TProperty>(Expression<Func<T, TProperty>> property) { _ = Sort == null ? Sort = items => items.OrderBy(property) : Sort = items => Sort(items).ThenBy(property); return this; }
Chaining or using separate lines doesn't make a difference.
This problem gets resolved if I assign a new instance of the specification and set it's func, but i don't want to be assigning to a new instance everytime. Please suggest what am i missing here and how to reuse the same instance (if possible).
-
How to projection fields for a dictionary (C#, MongdoDB)
I am trying my luck here, I have a model which is like the following
public class RowData : BaseBsonDefinition { . [BsonExtraElements] [BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)] public Dictionary<string, object> Rows { get; set; } = new(StringComparer.OrdinalIgnoreCase); . }
In result, the schema in the MongoDB looks like
{ "_id": { "$binary": { "base64": "HiuI1sgyT0OZmcgGUit2dw==", "subType": "03" } }, "c1": "AAA", "c8": "Fully Vac", "c10": "", }
Those c1, c8 and c10 fields are keys from the dictionary, my question is how to dynamic project those fields?
I tried
Builders<RowData>.Projection.Exclude(p => "c1")
It seems the MongoDB driver can not handle a value directly.
Anyone could point me in the correct direction?
Thanks,
-
How do I add new DataSource to an already Databinded CheckBoxList
i'm building a web form that show Database's item(Tables, Rows, FK,...)
I have a CheckBoxList of Tables (
chkListTable
) which will show a new CheckBoxList of Rows (chkListRow
) everytime I SelectedIndexChanged fromchkListTable
. The problem is i can show the items fromchkListTable
with 1 selected item. But i don't know how to showchkListRow
if multiple item fromchkListTable
are selected.Here are my codes:
aspx
:<div> <asp:Label ID="Label2" runat="server" Text="Table: "></asp:Label> <asp:CheckBoxList ID="chkListTable" runat="server" DataTextField="name" DataValueFeild="name" AutoPostBack="true" OnSelectedIndexChanged="chkListTable_SelectedIndexChanged"> </asp:CheckBoxList> </div> <div> <asp:CheckBoxList ID="chkListRow" runat="server" DataTextField="COLUMN_NAME" DataValueField="COLUMN_NAME" RepeatDirection="Horizontal"> </asp:CheckBoxList> </div>
aspx.cs
:protected void chkListTable_SelectedIndexChanged(object sender, EventArgs e) { tableName.Clear(); foreach (ListItem item in chkListTable.Items) { if(item.Selected) { tableName.Add(item.Text.Trim()); } } for(int i = 0; i < tableName.Count; i++) { String query = "USE " + dbname + " SELECT * FROM information_schema.columns" + " WHERE table_name = '" + tableName[i] + "'" + " AND COLUMN_NAME != 'rowguid'"; chkListRow.DataSource = Program.ExecSqlDataReader(query); chkListRow.DataBind(); Program.conn.Close(); } }
Program.cs
:public static bool Connect() { if (Program.conn != null && Program.conn.State == ConnectionState.Open) Program.conn.Close(); try { Program.conn.ConnectionString = Program.constr; Program.conn.Open(); return true; } catch (Exception e) { return false; } } public static SqlDataReader ExecSqlDataReader(String query) { SqlDataReader myreader; SqlCommand sqlcmd = new SqlCommand(query, Program.conn); sqlcmd.CommandType = CommandType.Text; if (Program.conn.State == ConnectionState.Closed) Program.conn.Open(); try { myreader = sqlcmd.ExecuteReader(); return myreader; myreader.Close(); } catch (SqlException ex) { Program.conn.Close(); return null; } }
I want my display to be like this:
[x]Table1 [x]Table2 [ ]Table3 [ ]Row1(Table1) [ ]Row2(Table1) [ ]Row3(Table1) [ ]Row1(Table2) [ ]Row2(Table2)
-
How do you manage runtime connection string in RepoDb using Dependency Injection in Web Api?
I'm developing Web API in .NET 6 using RepoDb (hybrid scenario: sql queries + orm entities).
I built a controller / service / repository architecture. I'm pretty new with DI. In appSettings.json I have all the possible connection strings and I get at runtime the key (instance name) to get the right one.
I need config (to extract appSettings.json data) and logging (NLog) in every architecture tier so I created a
BaseController
:[ApiController] public class BaseCustomController : ControllerBase { protected readonly IConfiguration Config; protected readonly ILogger<BaseCustomController> Logger; public BaseCustomController( IConfiguration config, ILogger<BaseCustomController> logger) { Config = config; Logger = logger; } }
Then I have my controller:
public class MyController : BaseCustomController { private readonly IMyService _myService; public MyController( IConfiguration config, ILogger<MyController> logger, IMyService myService) : base(config, logger) { _myService= myService; } [HttpPost] [Route("objects/object")] public async Task<BaseServiceResult> CreateComplexObject(MyViewModel myViewModel) { int newDocumentId = _myService.DoSomething(myViewModel); BaseServiceResult baseServiceResult = new BaseServiceResult(0, $"{newDocumentId}"); return baseServiceResult; } }
Then I have my Service. Here I have two possible ways:
public interface IMyService : IGenericService<MyClass> { }
or
public interface IMyService : IBaseService { }
and the relative implementations:
public class MyService : GenericService<MyClass> { public MyService( IConfiguration config, ILogger<MyService> logger, IGenericRepository<MyClass> myRepository) : base(config, logger, myRepository) { } public int DoSomething(MyViewModel myViewModel) { } }
or
public class MyService : BaseService, IMyService { private readonly IMyRepository _myRepository; public MyService( IConfiguration config, IMyRepository myRepository, ILogger<MyService> logger) : base(config, logger) { _myRepository = myRepository; } public int DoSomething(MyViewModel myViewModel) { _myRepository.Foo(); } }
where BaseService:
public abstract class BaseService { public BaseService(IConfiguration config, ILogger<BaseService> logger) { Config = config; Logger = logger; } }
In Middleware I get the instance name from the request and I store it in a
CommonInfoService
(is it correct or is it better to use other class type instead of Service?). Now how can I pass this information to every tier? Have I to inject CommonInfoService to every level?Where I must write the code to work with different tables? EG: Order and products: Must I work in the service or create a repo OrderProducts?
In this scenario I need methods use connection and eventually transaction. How can I use the instance name / connection string in Repository tier? I read about Unit Of Work.
public class MyRepository : GenericRepository<MyClass>, IMyRepository { public MyRepository(IConfiguration config, ILogger<MyRepository> logger) : base(config, logger) { } public IEnumerable<MyClass>> ListAllAsync<MyClass>() { using (var connection = new SqlConnection(InstanceConnectionString)) { var sql = "SELECT id, code from classes;"; Logger.LogDebug("Query: {sql}", sql); return connection.ExecuteQuery<MyClass>(sql); } } }
-
RepoDB doesn't merge correct after altering a column
With RepoDB I:
SqlServerBootstrap.Initialize(); using (var cnt = new SqlConnection(connectionString)) { cnt.ExecuteNonQuery("DROP TABLE IF EXISTS example"); cnt.ExecuteNonQuery("CREATE TABLE example(Id int NOT NULL PRIMARY KEY, Data nvarchar(1));"); cnt.Merge("example", new { Id = 1, Data = "a" }); //Adds a row cnt.ExecuteNonQuery("ALTER TABLE example ALTER COLUMN Data nvarchar(10);\n ALTER TABLE example ADD Name nvarchar(10);"); cnt.Merge("example", new { Id = 1, Data = "Long_word", Name = "A_name" }); //Updates the same row };
Result:
Id = 1 Data = "Lo", Name = NULL
Expected:
Id = 1 Data = "Long_word", Name = "A_name"
So RepoDB doesn't know that I have altered two columns. Is there a Flush() or Refresh(), so I can get RepoDB to know that I have made changes? Or can I write into RepoDB, what changes I have made?