我有一个静态类,我在其中使用字典作为查找表来映射.NET类型和SQL类型.这是一个这样的字典的例子:
private static readonly Dictionary<Type, string> SqlServerMap = new Dictionary<Type, string>
{
{typeof (Boolean), "bit"},
{typeof (Byte[]), "varbinary(max)"},
{typeof (Double), "float"},
{typeof (Byte), "tinyint"},
{typeof (Int16), "smallint"},
{typeof (Int32), "int"},
{typeof (Int64), "bigint"},
{typeof (Decimal), "decimal"},
{typeof (Single), "real"},
{typeof (DateTime), "datetime2(7)"},
{typeof (TimeSpan), "time"},
{typeof (String), "nvarchar(MAX)"},
{typeof (Guid), "uniqueidentifier"}
};
Run Code Online (Sandbox Code Playgroud)
然后我在下面有一个公共方法,它传入一个.NET类型,它使用这个字典返回相应的MS SQL Server类型的字符串值.但是,由于这被用作进行数据库查询的查找表,我认为将其作为一个有意义ConcurrentDictionary.我改成了:
private static readonly IDictionary<Type, string> SqlServerMap = new ConcurrentDictionary<Type, string>
{
{typeof (Boolean), "bit"},
{typeof (Byte[]), "varbinary(max)"},
{typeof (Double), "float"},
{typeof (Byte), "tinyint"}, …Run Code Online (Sandbox Code Playgroud) 所以我有这个办公室实体类:
[Table("office_entity")]
public class EFOffice : EFBusinessEntity
{
[Column("address")]
[StringLength(250)]
public string Address { get; set; }
[Column("business_name")]
[StringLength(150)]
public string BusinessName { get; set; }
public virtual ICollection<EFEmployee> Employees { get; set; }
public EFOffice(Guid id, Guid tenantId, string address, string businessName)
{
this.Id = id;
this.TenantId = tenantId;
this.Address = address;
this.BusinessName = businessName;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在实现一个通用存储库,我刚刚添加了这个方法来检查存储库中是否已存在实体:
public bool Exists<TEntity>(Guid key) where TEntity : class, IBusinessEntity
{
return (_context.Set<TEntity>().Find(key) != null);
}
Run Code Online (Sandbox Code Playgroud)
然后我写了以下测试代码:
public void TestExists1()
{
InitializeDatabase(); …Run Code Online (Sandbox Code Playgroud) 我有两种类型的实体:员工实体和办公室实体,两者之间有一对多关系,因此一个办公室有很多员工.对于EF,在每个实体的上下文文件中创建一个DbSet:
public DbSet<Office> Offices { get; set; }
public DbSet<Employee> Employees { get; set; }
Run Code Online (Sandbox Code Playgroud)
我做过的EF教程让我为特定实体做了我的CRUD方法.例如,下面的方法创建一个办公室并将其添加到办公室DbSet(忽略MVC的东西 - 我不再这样做了):
public ActionResult Create([Bind(Include = "Address,BusinessName")] Office office)
{
try
{
if (ModelState.IsValid)
{
db.Offices.Add(office);
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DataException /* dex */)
{
//Log the error (uncomment dex variable name and add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(office);
}
Run Code Online (Sandbox Code Playgroud)
基本上我要强调的两件事是将Office对象传递给方法,并通过显式编写db.Offices将Office添加到Office …
我正在使用实体框架,所以我相信我应该捕获一个,NpgsqlException因为它是 PostgreSQL 的 .NET 数据提供程序。假设我对上下文进行查询。如果PostgreSQL数据库中不存在该表,我想捕获抛出的异常,然后手动创建它。下面的代码是如何插入实体的示例,如果需要,我尝试使用错误处理来创建表:
try
{
return _context.Set(entityType).Add(entity);
}
catch (NpgsqlException)
{
CreateEntityTable(entity); //a private method I made
return _context.Set(entityType).Add(entity);
}
Run Code Online (Sandbox Code Playgroud)
问题是:
我不是 100% 确定我应该捕获 NpgsqlException
我想确保如果抛出异常,那是因为该表不存在。我查阅了错误代码的 PostgreSQL 文档,错误代码 42P01 是未定义的表。我相信我想用它,但是怎么用呢?我查找了NpgsqlException 类的成员,找到了 ErrorCode。然而,这是一个 int 类型。如果我可以将上面的代码更改为如下所示,那就太好了
try
{
return _context.Set(entityType).Add(entity);
}
catch (NpgsqlException ex)
{
if (ex.ErrorCode.Equals(42P01))
{
CreateEntityTable(entity); //a private method I made
return _context.Set(entityType).Add(entity);
}
}
Run Code Online (Sandbox Code Playgroud)但我不确定这是否有意义(我什至不确定 42P01 如何成为一个 int)。
任何帮助,将不胜感激。
我有以下代码行:
user.Exists = await this.repository?.Exists(id);
Run Code Online (Sandbox Code Playgroud)
Exists在左侧是User班级的财产.它的类型只是bool,而不是bool?.Exists右侧的方法是一种API方法,用于检查存储库中是否存在给定实体.它回来了Task<bool>.我想先检查存储库是否为null,因此我使用null条件运算符.我认为如果存储库为null,那么整个右侧只返回null,这不能分配给一个bool类型,但编译器似乎没问题.是否只是以某种方式默认为错误值?
我正在使用AWS JSONObject类.假设我JSONObject像这样定义一个对象:
JSONObject obj = new JSONObject();
obj.put("Field1": 35);
JSONObject nestedObj = new JSONObject();
nestedObj.put("Name1":"value1");
nestedObj.put("Name2":42);
obj.put("Field2": nestedObj);
Run Code Online (Sandbox Code Playgroud)
所以JSONObject看起来像:
{"Field1": 35,
"Field2": {"Name1": "value1",
"Name2": 42}
}
Run Code Online (Sandbox Code Playgroud)
我想采取这种方式JSONObject,并以某种方式将其转换为字节数组:
byte[] objAsBytes = convertToBytes(obj);
Run Code Online (Sandbox Code Playgroud)
哪个convertToBytes是正确执行此操作的函数.然后我想采用这个字节数组并将其转换回原始数据,JSONObject因此它仍保留其原始结构.
有谁知道如何做到这一点?我想这样做是因为我使用的是Amazon Kinesis,更具体地说是PutRecordAPI,并且PutRecordRequest要求数据是a ByteBuffer,所以我需要将其转换JSONObject为字节数组,然后将字节数组包装为ByteBuffer.然后,当我检索记录时,我需要将其转换ByteBuffer为字节数组,然后获取原始的JSONObject.
我觉得这必须是重复的,但我试过环顾四周,找不到我想要的东西.
我正在使用的示例从解析XML文档开始.在此XML文档中,人员的姓名在两个不同的位置陈述.后来用另一种方法,我需要使用这个人的名字.我可以在XML文档中使用这两个引用人名的任何一个,因为它们是相同的,或者我希望如此.我首先要检查它们是否确实相同.如果由于某种原因它们不相等,我觉得最好抛出异常.当一个人期望的两个值相等时实际上是不相等的,是否存在例外情况?
我考虑过ArgumentException,但我不确定这是否最好,因为它指定:
调用方法并且至少有一个传递的参数不符合被调用方法的参数规范时,抛出ArgumentException.
这不是这里的情况,因为参数很好,只是其中一个属性(即人名)的值不是我所期望的.
我想你可能遇到的第一个问题是我为什么要抛出异常.也许这不是最好的选择,但我认为应该考虑到两个名称不匹配的原因是因为当创建XML文档时,其中一个名称写入没有正确完成其工作,我可能想知道.我没有错误处理的经验,所以这可能并不意味着应该抛出异常.任何意见,将不胜感激.
我有两个有关 SignalR 集线器连接的相关问题,但在讨论它们之前,我将仅提供一些有关我正在做的事情的背景信息。
语境
我有一个使用 SignalR 将通知从服务器发送到前端(Javascript)客户端的应用程序。但是,还有一个后端 (.NET) 客户端可以创建中心的代理。后端客户端处理通知并将其发送到集线器,然后集线器将这些通知发送到前端客户端。
更具体地说,我有一个通知处理类,我们称之为NotificationProcessor.cs。每次创建新通知时,NotificationProcessor都会实例化一个实例。实例化后NotificationProcessor,将设置与集线器的代理连接。我有一个类,HubProxyService.cs它创建HubConnection对象并IHubProxy从中创建对象。其片段如下:
this.HubConnection = new HubConnection(serverUrl);
this.HubProxy = HubConnection.CreateHubProxy(hubName);
Task t = Task.Run(() => this.HubConnection.Start(new LongPollingTransport()));
t.WaitAndUnwrap();
Run Code Online (Sandbox Code Playgroud)
NotificationProcessor然后使用该IHubProxy对象调用集线器中的方法。
我发现HubConnection每次创建对象都会被实例化,并且在完成后NotificationProcessor不处理会导致内存泄漏。HubConnection
问题
(1)为了避免内存泄漏,我需要HubConnection以某种方式进行处置。我读到我可以做到
Task.Run(() => this.HubConnection.Stop())
Run Code Online (Sandbox Code Playgroud)
问题是我不知道什么时候可以调用它。由于使用代理调用 hub 方法是异步的,我可以在调用 hub 方法后立即调用它吗?或者,如果从集线器向前端客户端发送通知出现延迟,这是否会导致问题?
我想另一种选择是将 HubConnection 初始化包装在 using 语句中,如下所示
using (HubConnection connection = new HubConnection(serverUrl))
{
}
Run Code Online (Sandbox Code Playgroud)
我听说这也可能有问题,因为处理HubConnection可能需要一段时间。
有一个比另一个更好吗?后者似乎更惯用,而前者更明确并且可能效果更好。
(2) 为创建的HubConnection每个实例创建 …
假设我有这本字典:
Dictionary<Guid, Person> people = new Dictionary<Guid, Person>();
Run Code Online (Sandbox Code Playgroud)
假设其中填充了一些数据。我们也说Person有一个Ssn属性。我想在人与回报的人Ssn = socialSecurityNum,其中socialSecurityNum一些价值。这是我要做的最好的主意:
public Person GetPerson(int socialSecurityNum)
{
IEnumerable<Person> persons = people.Values.Where(p => p.SSN == socialSecurityNum);
foreach (Person person in persons)
{
return person;
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
我知道每个人都有不同的Ssn,所以我只返回列表中第一个值(因为列表只是一个值)。否则返回null。
我对此解决方案不满意的是,我必须从linq查询中获取一个列表,而不是单个值。是否有可以从字典中获取单个值的linq查询?
c# ×8
dictionary ×2
.net ×1
boolean ×1
bytearray ×1
constructor ×1
database ×1
entity ×1
exception ×1
generics ×1
idictionary ×1
java ×1
json ×1
lambda ×1
linq ×1
memory-leaks ×1
npgsql ×1
nullable ×1
postgresql ×1
private ×1
signalr ×1
signalr-hub ×1