首页 \ 问答 \ 使用Entity Framework时实现业务逻辑(implementing business logic when using Entity Framework)

使用Entity Framework时实现业务逻辑(implementing business logic when using Entity Framework)

我是Entity框架的新手,我对如何实现业务逻辑感到困惑。

我正在使用Code First方法并生成了我的POCO。 我将它们放在一个单独的项目中,这样它们就可以用在多个项目中。

我想知道如何实现对象的业务逻辑,当我尝试将项目保存到数据库时检查。 例如,如果我定义一个规则,除非输入名称,否则无法保存MyObject,我该怎么做?

示例简单的POCO

public class MyObject() {
    public String name { get; set; };

    public MyObject() {}
}

显然我有很多对象,每个对象都有不同的业务规则。

我来自Csla( http://www.lhotka.net/cslanet/ )业务框架背景,您可以在其中定义一个具有Save方法的业务对象。 在调用Save时,框架运行ValidationRules,从而确定是否需要调用数据库。

我希望使用Entity Framework这样的东西。 代码示例很棒,或者对阅读材料的引用。 谢谢


I am new to Entity framework and am getting confused about how to implement Business Logic.

I am using the Code First approach and have generated my POCOs. I have them in a separate project so they can be used in multiple projects.

I would like to know how i can implement business logic for an object, that is checked when i try to save an item to the database. For example, if I define a rule that MyObject cannot be saved unless a name is entered, how can i do this?

Example simple POCO

public class MyObject() {
    public String name { get; set; };

    public MyObject() {}
}

Obviously i have many objects, and each object has different business rules.

I am coming from a Csla (http://www.lhotka.net/cslanet/) business framework background, where you define a business object, which has a Save method. upon calling Save, the framework runs the ValidationRules and thus determines whether a call to the database is needed.

I would like something like this, using Entity Framework. Code example would be great, or references to reading material. Thanks


原文:https://stackoverflow.com/questions/25788757
更新时间:2023-07-24 17:07

最满意答案

在原始的json上,消息列表位于名为“messages”的字段中。 这就是为什么你需要做[消息]以获得对应于“消息”键主体的JToken。

从现在开始,您直接在更高级别上有一个列表,可能更容易直接使用JsonConvert,将您的字符串反序列化为Message对象列表(使Message成为具有名为MessageID,Name,Subject等的字段的类)。 )。

List<Message> message = JsonConvert.DeserializeObject<List<Message>>(content);

另请注意,如果您遵循此方法,并且您的Message类具有与Json略有不同名称的字段,则需要添加注释以便为解析提供正确的名称,例如:

[JsonProperty("MessageID")]
public string MessageId { get; set; }

在任何情况下,如果您更倾向于以其他方式进行解析,那么在可能的情况下保留旧的json可能更好,主要是因为命名字段总是优先于只有无密钥无名对象。


On your original json, the list of messages was inside a field called "messages". That's why you needed to do [messages] to obtain the JToken corresponding to the body of the "messages" key.

Since now you have directly a list on the higher level, it's probably easier to just fall down to using JsonConvert directly, deserializing your string into a List of Message objects (Having Message be a class having fields named MessageID, Name, Subject, etc.).

List<Message> message = JsonConvert.DeserializeObject<List<Message>>(content);

Be aware, also, that if you follow this approach, and your Message class has fields with slightly different name than the Json, you will need to add annotations for providing the proper name to the parse, like:

[JsonProperty("MessageID")]
public string MessageId { get; set; }

In any case, if you'd rather to the parsing some other way, it's probably better to just keep your old json when possible, mostly because named fields are always preferred to just having keyless-nameless objects.

相关问答

更多
  • 您可以使用Json.net JsonConvert.DeserializeObject函数 创建一个ObjModel类来承载您的json数据。 public class ObjModel { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("date")] public string Date { get; set; } [JsonProperty("name")] pub ...
  • Restsharp提供开箱即用的反序列化。 只需创建一个映射你的json的类。 public class MyModel { public int Id {get; set;} public string Content {get; set;} } 然后使用Execute而不是Execute 。 var response = client.Execute(request); var model = response.Data; 然后你可以很容易地设置文本: MyE ...
  • 尝试将异步代码移出构造函数。 常见的方法是重写OnAppearing()来执行工作。 您可能还希望在UI中显示ActivityIndicator ,直到加载数据为止: public partial class ContactInfo : ContentPage { private County item; public static async Task GetContactString(string contactid) { HttpClient ...
  • 为了缩小问题范围,首先向google.com等第三方服务器发送简单的get请求,同时不指定Accept或ContentType 。 如果超时没有重现,那么你可能在隐藏在url后面的服务器上遇到问题。 如果超时仍然存在,则可能是客户端(设备/模拟器)上存在问题,或者介于Web代理/ wifi路由器/等之间。 为了检查后者,请从您的PC(即标准浏览器)发出相同的请求。 它快速检索响应吗? In order to narrow down the problem start with a simple get re ...
  • 你需要反序列化JSON字符串 var data = JsonConvert.DeserializeObject(jsonString); 然后运行foreach循环 foreach(var orders in data) { var Id = orders.order.orderId; ///and so on... } You need to Deserialize JSON string var data = JsonConvert.DeserializeOb ...
  • 如果链接器因“找不到类型等等”而失败,那么这通常意味着您在应用程序的某个地方使用了桌面.Net库。 如果它是JSON.Net,请删除桌面程序集并在组件存储上使用JSON.Net的版本(这是Xamarin的NuGet版本,除了一些支付的东西)。 我还要确保你有最新版本的Xamarin.Android。 If the linker fails with "failed to find type blah blah", then this normally means you are using a deskto ...
  • 您希望为列表视图设置适配器的方式不会那样。 在foreach循环中设置listview的adapter属性是完全错误的。 这同样适用于您的文本视图。 您需要实现一个自定义适配器,为每个轨道列表项加载布局。 您的自定义适配器可能看起来像下面的示例,我已经写出了我的想法,没有进一步测试。 但它实现了自定义适配器需要实现的必需方法。 重要的部分是GetView方法,每当listview要求新项目表示时,它返回您的轨道布局。 为了保持应用程序内存不足,它使用ViewHolder模式,如果要使用RecycleView ...
  • public override View GetView(int position, View convertView, ViewGroup parent) { TableItem item; if (position == 0 { item = new TableItem { DDLValue = "Select" }; } else { item = items[position - 1]; ...
  • 在原始的json上,消息列表位于名为“messages”的字段中。 这就是为什么你需要做[消息]以获得对应于“消息”键主体的JToken。 从现在开始,您直接在更高级别上有一个列表,可能更容易直接使用JsonConvert,将您的字符串反序列化为Message对象列表(使Message成为具有名为MessageID,Name,Subject等的字段的类)。 )。 List message = JsonConvert.DeserializeObject>(cont ...
  • 请试试这个: public async void DownloadDataAsync() { try { string url = "http://myWebSite.com/jWebService.asmx/GetOffersJSON?storeID=2"; var httpClient = new HttpClient(); var content = await httpClient.Ge ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)