开发者

Regular Expression Challenge: Modify this line of C#

I am developing a RIA Domain Service that will use a POCO Entity Data Model. There is some fixup required with the default Domain Service template due to the fact that POCO classes do not implement the EntityState property, as does EntityObject.

Julie Lerman provides the solution:

 OLD: if ((customer.EntityState == EntityState.Detached)) 
 NEW: if ((GetEntityState(customer) != EntityState.Detached))

The problem is that I may have to regenerate the domain service several times over the course of my development, and there are lots of tables/entities to deal with.

The Question:

Can the "OLD" above be replaced with the "NEW" using a regex? It's a very predict开发者_JS百科able pattern:

  1. Find instances of '.EntityState'
  2. Replace with 'GetEntityState([text between ( and .])'


Using Visual Studio Find and Replace (and with Use Regular Expressions on, of course):

Find what: if \(\({:i}\.EntityState == EntityState\.Detached\)\)

Replace with: if ((GetEntityState(\1) == EntityState.Detached))

Edit

The OP seems to prefer Expresso. In that case it would be like this:

Regular Expression: if \(\((\w+)\.EntityState == EntityState\.Detached\)\)

Replacement String: if ((GetEntityState($1) == EntityState.Detached))

(Also fixed the != typo)


s/(\w+)\.(EntityState)/Get\2(\1)/

edit: you didn't ask to flip == to !=, but I'm not sure it should be as that would be the opposite functionality

edit 2: also, if you want to do this multiple times on a line potentially, add a g at the end


If you have ReSharper, you can use its Structured Search and Replace feature for this. Then you'll catch places other than if statements -- it will be smart enough to find any expression that refers to an EntityState property, and transform it to a method call. You can even restrict it to certain classes if you like, though it sounds like that may not be necessary in this case.

  1. Go to ReSharper > Find > Search with Pattern
  2. In the "Search pattern" box, type: $obj$.EntityState
  3. Above the right listbox, click "Add Placeholder > Expression". Enter obj for the name. Leave "Expression type" blank, or if you want to narrow the search, enter your POCO's type name. Click OK.
  4. Click the "Replace" button in the top right. For the "Replace pattern", type: GetEntityState($obj$)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜